How we select data from SDF (webmatrix) database in visual studio with Linq just like we can with northwind, like this:?
// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(#"northwnd.mdf");
// or, if you are not using SQL Server Express
// Northwnd nw = new Northwnd("Database=Northwind;Server=server_name;Integrated Security=SSPI");
var companyNameQuery =
from cust in nw.Customers
where cust.City == "London"
select cust.CompanyName;
foreach (var customer in companyNameQuery)
{
Console.WriteLine(customer);
}
Ref: http://msdn.microsoft.com/en-us/library/bb399398.aspx
please thank you for your help.
I don't believe that Linq To SQL is officially supported with SQL Server CE 4.0, although it appears you can get it working. Microsoft's recommended approach is to use the Entity Framework.
I've written a couple of articles on using EF with SQL Server CE in WebMatrix. One covers the Code First approach, and the other looks at a database first approach.
Related
I have a WinForms database driven application that I want to make it work in online/offline mode using Dotmim sync framework that I find an article by their author here.
The documentation for the library is here
this is my code to sync the two SQL Server databases one is localdb and the other one is now on the SQL Server Management Studio for the testing purpose:
string connect = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=bright_square_db;Integrated Security=SSPI;AttachDBFilename=D:\Folder\project_file\bright_square_db.mdf";
string constring = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlSyncProvider serverProvider = new SqlSyncProvider(constring);
SqlSyncProvider clientProvider = new SqlSyncProvider(connect);
SyncAgent agent = new SyncAgent(clientProvider, serverProvider, new string[] { "I have listed all the tables here" });
var progress = new SynchronousProgress<ProgressArgs>(s => MessageBox.Show($"{s.Context.SyncStage}:\t{s.Message}"));
var syncContext = await agent.SynchronizeAsync(progress);
MessageBox.Show(syncContext.ToString());
But, when I try to run the code. I am getting this error
The columns that indicated in the error are for a table that created by the sync process named "scope_info" inside the SQL Server database.
I have solved the problem by swapping the client and server connection string link in the third and fourth line of the above code. I don't know what exactly cause the problem, but lastly this changed makes the code work for me.
I have a database with three tables in it. I created all the tables within Visual Studio. My C# code is connecting to the database using Linq to SQL. The table I am having problems with is not updating on SubmitChanges().
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
tbl_Inventoryv2 inv = new tbl_Inventoryv2();
inv.Title = addTitleTextBox.Text;
inv.Model = addModelTextBox.Text;
inv.Category = addCategoryTextBox.Text;
inv.Quantity = int.Parse(addQuantityTextBox.Text);
inv.Price = decimal.Parse(addPriceTextBox.Text);
inv.Description = addDescriptionTextBox.Text;
db.tbl_Inventoryv2s.InsertOnSubmit(inv);
db.SubmitChanges();
int id = inv.IdInventory;
MessageBox.Show($"Item creation successful. Item number is {id}");
}
My database does have a primary key called IdInventory that is set to increment. Within the program, the correct increments are working as shown in my MessageBox statement above, but it never actually gets saved to the database. I have also checked the properties of the database file in Visual Studio and the path to the database is correct, as well as the Copy to Output Directory is set to Copy if Newer. Most of the questions I have looked up indicate that is usually the problem, but that doesn't look like the case for me. I am new to SQL and interacting with it via Visual Studio/c#, and SQL in general, so any input is greatly appreciated.
Quick one right here: I used Entity Framework's database-first approach so all the classes are automatically generated.
I am delivering the application on Monday, I was thinking that it would be better to generate the database on the first launch of the app.
Is this doable? I know it possible if you are using the code-first approach.
So I thought it is reciprocal.
If it helps I am using SQL Server 2014, Visual Studio 2015, C#, Entity Framework, Winforms.
var scsbCentral = new SqlConnectionStringBuilder(connectionString);
var ecbCentral = new EntityConnectionStringBuilder();
ecbCentral.Metadata = "res://*/KBSCentral.csdl|res://*/KBSCentral.ssdl|res://*/KBSCentral.msl";
ecbCentral.Provider = "System.Data.SqlClient";
scsbCentral.MultipleActiveResultSets = true;
ecbCentral.ProviderConnectionString = scsbCentral.ConnectionString;
var CentralContext = new KBS_CentralEntities(ecbCentral.ConnectionString);
if (!CentralContext.Database.Exists())
{
CentralContext.Database.Create();
}
I use C#, .net 4, Entity Framework and SQL Server 2008 R2 in a project.
I have no familiarity with backup and restore from database by Entity Framework. Please help me to write restore and backup code in Entity Framework
Entity Framework is an ORM - object-relational mapper - designed to handle interactions with single entities and/or short lists of entities. It's neither designed for bulk operations, nor is it a server admin framework. So no - I don't think you can do this using Entity Framework - that's not its job.
Use an appropriate tool for the job! Either use SQL Server Management Studio to handle backup/restore - or if you must do it programmatically, use the SMO (Server Management Objects) which is intended for exactly these kinds of jobs
To other friends who have this problem ....
Useing ExecuteSqlCommand can backup of db in EF 6+ .
For example : (this code create backup of your DB , I had tested this.)
string dbname = db.Database.Connection.Database;
string sqlCommand = #"BACKUP DATABASE [{0}] TO DISK = N'{1}' WITH NOFORMAT, NOINIT, NAME = N'MyAir-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
db.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, string.Format(sqlCommand,dbname, "Amin9999999999999"));
backup saved in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup
ref=> https://entityframework.codeplex.com/discussions/454994
but I do not recommend for working with this method!
I strongly recommend the use of the article below:
http://www.c-sharpcorner.com/Blogs/8679/backup-and-restore-the-database-in-Asp-Net-web-application.aspx
This should get you going on the restore side:
void LoadDB(
System.Data.Entity.DbContext context,
string backup_filename,
string orig_mdf, // the original LogicalName name of the data (also called the MDF) file within the backup file
string orig_ldf, // the original LogicalName name of the log (also called the LDF) file within the backup file
string new_database_name
)
{
var database_dir = System.IO.Path.GetTempPath();
var temp_mdf = $"{database_dir}{new_database_name}.mdf";
var temp_ldf = $"{database_dir}{new_database_name}.ldf";
var query = #"RESTORE DATABASE #new_database_name FROM DISK = #backup_filename
WITH MOVE #orig_mdf TO #temp_mdf,
MOVE #orig_ldf TO #temp_ldf,
REPLACE;";
context.Database.ExecuteSqlCommand(
// Do not use a transaction for this query so we can load without getting an exception:
// "cannot perform a backup or restore operation within a transaction"
TransactionalBehavior.DoNotEnsureTransaction,
query,
new[] {
new SqlParameter("#backup_filename", backup_filename),
new SqlParameter("#database_dir", database_dir),
new SqlParameter("#new_database_name", new_database_name),
new SqlParameter("#orig_mdf", orig_mdf),
new SqlParameter("#orig_ldf", orig_ldf),
new SqlParameter("#temp_mdf", temp_mdf),
new SqlParameter("#temp_ldf", temp_ldf),
}
);
}
If you don't know them beforehand, the MDF and LDF LogicalName values can be obtained manually or programmatically from a query like this one:
RESTORE FILELISTONLY FROM DISK #backup_filename
Using .NET's DbConnection.GetSchema(), how do I find the owner of a given database?
Alternatively, if you have another solution that is not coupled to a specific impelementation of SQL, I'd like to hear that as well.
The GetSchema call of DbConnection unfortunately doesn't retrieve the DB owner for you :-(
But you can try this on SQL Server:
select
db.name, db.database_id, l.name, l.type
from
sys.databases db
inner join
sys.login_token l on db.owner_sid = l.sid
If you want to connect to SQL Server from .NET, you could use the SMO (SQL Management Objects) and find your owner like this:
Server server = new Server("Your Server");
Database db = server.Databases["Your Database"];
Console.WriteLine("Database owner is: " + db.Owner);
Marc
I don't believe that the SQL-92 standard specifies that a Catalog (a database) must have an owner. As such, I don't know that you can get a non-implementation-specific way of doing this.