Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4.1 is not adding any rows to SQL Server Express database

Working with Entity Framework 4.1 with a SQL Server Express .mdf database .

For test purpose I am trying to perform CRUD operations on SQL Server Express database using Entity Model in a WPF application .

I am new to this concept, and I followed the video tutorial and done coding according that

I created Entity model of single very simple table. And I wrote simple code in cs file to perform adding one row to the database using following code

testEntities db = new testEntities();
TestTable tb = new TestTable();
tb.Name = txtName.Text;
tb.Email = txtMail.Text;
db.TestTables.AddObject(tb);
db.SaveChanges();

But if I go back check the database no data is added. Please tell me whats going wrong here ??

And here is my connection String

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="testEntities" 
         connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\test.mdf;integrated security=True;connect timeout=30;user instance=True;multipleactiveresultsets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>
like image 563
panindra Avatar asked Jul 18 '12 18:07

panindra


1 Answers

The whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file (from the DataDirectory to the output directory of your running app) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!

If you want to stick with this approach, then try putting a breakpoint on the .SaveChanges() call - and then inspect the .mdf file in the running app's directory with SQL Server Mgmt Studio Express - I'm almost certain your data is there.

The real solution in my opinion would be to

  1. install SQL Server Express (and you've already done that anyway)

  2. install SQL Server Management Studio Express

  3. create your database in SSMS Express, give it a logical name (e.g. TestDatabase)

  4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:

    Data Source=.\\SQLEXPRESS;Database=TestDatabase;Integrated Security=True
    

    and everything else is exactly the same as before...

like image 196
marc_s Avatar answered Oct 18 '22 13:10

marc_s