简体   繁体   中英

Entity Framework not saving changes to a Local DB

I'm new to C# and Entity Framework and I'm trying to write an application to improve my knowledge.

I think I've set up everything correctly and I don't get any type of error. The problem is that I can not add a new record to localDb in Visual Studio 2017.

Any ideas? Thanks in advance.

Here is my code

private void Save_btn_Click(object sender, EventArgs e)
{
        var context = new Database1Entities();

        var aMemberdef = new Members()
        {
            FirstName = Name_txt.Text,
            LastName = LastName_txt.Text
        };

        context.Members.Add(aMemberdef);
        context.SaveChanges();
}

and here my app.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="entityFramework" 
                 type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
                 requirePermission="false" />
    </configSections>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <connectionStrings>
        <add name="Database1Entities" 
             connectionString="metadata=res://*/EF.Model1.csdl|res://*/EF.Model1.ssdl|res://*/EF.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\MSSQLLocalDB; attachdbfilename=|DataDirectory|\Data\Database1.mdf; initial catalog=Database1; integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
             providerName="System.Data.EntityClient" />
    </connectionStrings>
    <entityFramework>
        <defaultConnectionFactory  
             type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
        <providers>
            <provider invariantName="System.Data.SqlClient" 
                      type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
    </entityFramework>
</configuration>

I think there is some mistake in the app config file but the connection string was generated by entity framework. So I'm stuck MyDB Structure

Because your localdb is copied to bin folder every time you run it. It gets overwritten everytime you run/debug it. Main file in the project folder is not updated. For detailed answer: https://social.msdn.microsoft.com/Forums/en-US/393bddc6-0b85-4c27-9475-27172e50d2d9/entity-framework-doesnt-save-new-record-into-database?forum=adodotnetentityframework

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM