Entity Framework not saving changes to a Local DB - c#

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="data source=(LocalDB)\MSSQLLocalDB; attachdbfilename=|DataDirectory|\Data\Database1.mdf; initial catalog=Database1; integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
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

Related

How to handle "No connection string named 'RestaurentEntities' could be found in the application config file" in WinForms

I am trying a project on WinForms. I made a Form name Dashboard and User Control name DashboardScreen.
Dashboard basically will have many User Controls on it like DashboardScreen, InventoryScreen, SettingsScreen etc. These screens are small and Dock in main parent form Dashboard so when user click on button, corresponding user control comes to the front using DashboardScreen.BringToFront()
These user controls are implementing Entity Framework V 6.4.0 User controls and Main Dashboard Form works fine when I do not use Entity Framework on these controls. Whenever I use Entity Framework as RestaurentEntities DB = new RestaurentEntities(); to utilize database services the Main Dashboard Form gives the following Error in Design Mode.
No connection string named 'RestaurentEntities' could be found in the application config file.
Second Error is
The variable 'dashboardScreen' is either undeclared or was never assigned.
Given is my configuration file.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings><add name="RestaurentEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=YASIR\SQLDEVENV;initial catalog=Restaurent;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
if you want to drag and drop a UserControl in a form and the control in the constructor method or OnLoad method has access to EntityFramework and the EntityFramework access is created by referenced project you must include into your code something like:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!DesignMode)
{
//access to EntityFramework
}
}
Change your connectionStrings to below:
<connectionStrings>
<add name="RestaurentEntities"
connectionString="data source=YASIR\SQLDEVENV;initial catalog=Restaurent;integrated
security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
And make sure that
your Dbcontext constructor is like
public RestaurentEntities ()
: base("name=RestaurentEntities")
{
}

'Option not supported' error when using SQL Server with MySQL

I'm trying to retrieve data from both MySQL and SQL Server on the same console application. I manage to retrieve data from MySQL, however when I trying to retrieve data from SQL Server, I got System.ArgumentException: 'Option not supported. Parameter name: multipleactiveresultsets' error.
The following is 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.6.1" />
</startup>
<connectionStrings>
<add name="MySQLDb" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=sakila;uid=some_user;password=some_password"/>
<add name="SQLDb" providerName="System.Data.SqlClient" connectionString="data source=USER-PC\SQLEXPRESS;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"/>
</connectionStrings>
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
</configuration>
And my C#:
#region MySQL.
{
var dbContext = new MySQLDb();
var dbSet = dbContext.Set<Actor>();
var actors = dbSet.ToList();
}
#endregion
#region SQLServer.
{
var dbContext = new SQLDb();
var dbSet = dbContext.Set<User>();
var users = dbSet.ToList(); // <-- Throw exception.
}
#endregion
If I disable entityFramework section in app.config and MySQL code block in my C# code, I can retrieve data from SQL Server without any issue.
Version info
MySQL.Data.Entity 6.10.8
NET Framework 4.6.1
Any idea?
Update 1
Found out that the connection type for MySQLDb is MySql.Data.MySqlClient.MySqlConnection, so that works just fine. But when instantiating SQLDb, the connection type is still MySql.Data.MySqlClient.MySqlConnection instead of System.Data.SqlClient.SqlConnection. How should we fix this?
The issue is that we are using MySql.Data.Entity.MySqlEFConfiguration (in the app.config) which set the default connection factory to use MySqlConnectionFactory.
The solution is to use a custom DbConfiguration in place of MySql.Data.Entity.MySqlEFConfiguration to deter from setting the default connection factory.
public class MySQLDbConfiguration : DbConfiguration
{
public MySQLDbConfiguration()
{
SetProviderServices(MySqlProviderInvariantName.ProviderName, new MySqlProviderServices());
SetProviderFactory(MySqlProviderInvariantName.ProviderName, new MySqlClientFactory());
}
}
Declare the instance as readonly somewhere in the code,
private static readonly MySQLDbConfiguration DBConfig = new MySQLDbConfiguration();
and set the configuration PRIOR TO using any EF features
DbConfiguration.SetConfiguration(DBConfig);
And our app.config now becomes
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="MySQLDb" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=sakila;uid=some_user;password=some_password"/>
<add name="SQLDb" providerName="System.Data.SqlClient" connectionString="data source=USER-PC\SQLEXPRESS;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"/>
</connectionStrings>
</configuration>
If you're opt to use app.config instead of deriving a custom DbConfiguration, you can do the following
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- Alternative to custom DbConfiguration. -->
<configSections>
<section name = "entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<providers>
<provider invariantName = "MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant = "MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</DbProviderFactories>
</system.data>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="MySQLDb" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=sakila;uid=some_user;password=some_password"/>
<add name="SQLDb" providerName="System.Data.SqlClient" connectionString="data source=USER-PC\SQLEXPRESS;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"/>
</connectionStrings>
</configuration>
If you are using asp net 5.0, install the Nuget found here, but first uninstall Mysql.data.

Migrate database generated by entity framework to sqlserver

I made a application with database generated by entity framework(code first) and now I want to make my application working on other computer. I instaled sqlserver there and made all the tables in the database (I am working just with localhost database). Now I wanted to connect my database with application, I thought that all what I need to do is just change connection string. But I am not able to connect to my database.
Here is how looks my app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<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="InzerceConnection" connectionString="Data source=VRBASPC\SQLEXPRESS;Initial Catalog=AdvertisingSystemDB;Trusted_Connection=true;MultipleActiveResultSets=true" />
<!--This is how my connection string works by default <add name="InzerceConnection" connectionString="Server=(localdb)\\MSSQLLocalDb;Database=Inzerce_Dev;Trusted_Connection=true;MultipleActiveResultSets=true" />-->
<!--<add name="InzerceConnection" connectionString="Server=localhost\SQLEXPRESS;Database=AdvertisingSystemDB;Trusted_Connection=true;MultipleActiveResultSets=true" />-->
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I tried a lot of combination of connection string, but none worked.
I am not sure how to setup my config file to connect to database.
Thank you for any advice.
Sory for my english its not my native language.
In your context override the OnConfiguring method.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connstr = ConfigurationManager.ConnectionStrings["InzerceConnection"].ToString();
optionsBuilder.UseSqlServer(connstr);
}
Check in your database context.
Database context and name attributes should be the same.
For Example
public class DatabaseContext : DbContext
{
public DbSet<Content> Contents { get; set; }
public DbSet<Category> Categories { get; set; }
public DatabaseContext()
{
Database.SetInitializer(new MyInitializer());
}
}
ConnectionStrings in your app.config
<connectionStrings>
<add name="DatabaseContext" providerName="System.Data.SqlClient" connectionString="Data source=VRBASPC\SQLEXPRESS;Initial Catalog=AdvertisingSystemDB;Trusted_Connection=true;MultipleActiveResultSets=true" />
</connectionStrings>

Deploy a WPF program and update the database if required

I'm creating a WPF application that uses a LocalDB instance (which is provided by the ClickOnce installer).
The program uses a database to store userdata. When the application is deployed for the very first time, I want to create a LocalDB where some data is inserted upon initialization.
When I later provide an update to the program (which may include schema changes), I do not want to lose any userdata.
I'm using EF Code-First and this is my DbContext:
public class MyContext : DbContext
{
public DbSet<Stuff> Premises { get; set; }
public DbSet<Person> Persons { get; set; }
private static MyContext _Current;
public static MyContext Current
{
get
{
if (_Current == null)
{
_Current = new MyContext();
}
return _Current;
}
}
protected MyContext()
{
//Some data to insert on the first time
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Stuff>().HasMany(p => p.Persons).WithRequired(m => m.Stuff);
}
}
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<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" />
</startup>
<connectionStrings>
<add name="MyContext"
connectionString="data source=(LocalDB)\mssqllocaldb;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Am I correct in thinking that adding my development .mdf file will always overwrite the userdata when I update via ClickOnce?
How can I let EF create the schema for the first time, update when there's changes, and never lose any userdata?

app.config: ConnectionString value not visible in project where it's defined

Hi I have a few projects in Solution.
In project A, I have app.config with connection string called Ver3ConnectionString. But when I do debug, the connection string is not found in code:). While debugging connection strings contains one which is not defined in this app.config, nether in my app :). Im using VS2013 Express :).
Moreover, applicationSettings are ones which are defined in main project:), but not one which is being dubugged.
Magic:).
ADDED:
THe solution was created by my coworker from existing project, so Im looking for error in solution/project files.
MobileWalletContext class is connected with EntityFramework 6.X. Maybe this is the problem?
Added 2:
This unknown connection string has name ="LocalSqlServer". Maybe this will be helpful?
App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="Ver3ConnectionString"
connectionString="Data Source=PAZI-PRO2\SQLEXPRESS;Initial Catalog=MobileWalletVer3;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
C# code where connsterionString is called:
public MobileWalletContext() : base(string.Format("name={0}",ConfigurationManager.ConnectionStrings["Ver3ConnectionString"].ConnectionString))
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MobileWalletContext>());
}
Name of the connection string is not likely to change. Therefore I would simplify context constructor to:
public MobileWalletContext() : base("Ver3ConnectionString")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MobileWalletContext>());
}
That way I could define different connection string in each project using Ver3ConnectionString name.
EDIT
DbContext base constructor accepts both connection string name or full connection string.
In your case instead of referencing existing connection string you are just creating a new connection string with provided name and default settings. Thats why you are seeing LocalSqlServer.
If you pass name of existing connection string in config, it will be picked up and used.
EDIT
Make sure your connection strings are in app.config or web.config file in your main project directory.
I'd like to add this to what #Kaspars-Ozols wrote:
LocalSqlServer is your SQL Express installation and its configuration usually resides in a machine.config file like C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config. You may have more than 1 machine.config [2 runtimes (2.0 and 4.0)] x [2 Bitness (x86 and x64)] makes 4 machine.config files!
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
It's a good habit to use <clear /> at the very beginning of <appSettings> or <connectionStrings> sections.
<connectionStrings>
<clear/>
<add name="MembershipConnection" connectionString="Server=.;UId=some_user;PWd=P#$$w0rd;Database=DBName" providerName="System.Data.SqlClient" />
<add name="ElmahConnection" connectionString="Server=.;UId=some_elmah_user;PWd=P#$$w0rd;Database=DBName" providerName="System.Data.SqlClient" />
</connectionStrings>

Categories

Resources