Entity Framework To A Remote Server (Connection String) - c#

I have installed EF Version 6.1.3 on all my projects. I then created a model class, a context class, and installed a MSSQL database on my local computer (I did not have done anything else). Everything worked just perfectly (somehow it knew about my local database).
Model class:
public class Account
{
public int Id { get; set; }
public string Name{ get; set; }
}
DataContext class:
public class MyClassDataContext: DbContext
{
public DbSet<Account> Accounts{ get; set; }
}
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=xxxxxx" requirePermission="false" />
</configSections>
<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 then tried to move it to a remote database and it doesn't work. I tried everything.
What is the right approach, to get the job done?
EDIT:
I tried this connection string and nothing happens. The app still tries to connect with the local database.
<connectionStrings>
<add name="MyClassDataContext" connectionString="Data Source=MyRemoteServer;Initial Catalog=MyRemoteCatalog;Integrated Security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
<configSections>

You need to create either make sure that your connections string's name is the fully qualified name of your context, or create an explicit default constructor for your context. Since you mentioned it in the comments, the link you provided isn't working for you because you're using code-first. Try this link instead.
Below is a fully functional console app that can demonstrate how it should work, along with the config file. This will use our local SQLServer installation, but not the SQLExpress. It should work fine for any remote database as well.
Note that in the previous app config that I had posted, I put the connection string section at the top. That is incorrect: configSections must be the first node.
namespace TestApp
{
public class Account
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyClassDataContext : DbContext
{
public DbSet<Account> Accounts { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var x = new MyClassDataContext())
{
x.Accounts.Add(new Account { Name = "Drew" });
x.SaveChanges();
var y = x.Accounts;
foreach (var s in y)
{
Console.WriteLine(s.Name);
}
}
Console.ReadKey();
}
}
}
The configuration file:
<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="ConsoleApplication4.MyClassDataContext" connectionString="Data Source=.;Initial Catalog=MyClass;Integrated Security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
<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>
</configuration>

Related

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>

Entity Code First Error (Mysql)

When I run "Enable-Migrations -Force" command on my Class Library project, I see following error.
Note: Mysql.Data and Mysql.Data.Entity has been installed.
System.TypeInitializationException: The type initializer for
'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an
exception. ---> System.TypeLoadException: Inheritance security rules
violated by type: 'MySql.Data.Entity.MySqlEFConfiguration'. Derived
types must either match the security accessibility of the base type or
be less accessible.
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" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=10.10.10.10;Database=dbName;Uid=user;Pwd=p;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<!--<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />-->
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
</provider></providers>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
DbContext.cs
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext : DbContext
{
public MyDbContext() : base("DefaultConnection")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Board> Boards { get; set; }
}
I'm having exactly the same problem in both VS 2015 and VS 2017, have tried everything and nothing works :(
--- Edit
I get the job done after downgrade the MySQL.Data to 6.8.8.0 . Worked both VS 2015 and VS 2017.
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class Context : DbContext
{
public Context() : base("MyContext")
{
}
public DbSet<Foo> foo;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Foo>();
}
}

Specifying database connection string for EntityFramework6.Npgsql - Code First

I have an issue regarding the .NET postgreSQL provider package EntityFramework6.Npgsql. I have installed the following packages: EntityFramework 6.0.0, EntityFramework6.NpgSql 3.1.1, Npgsql 3.1.0.
Currently I have just started a WPF project so I'm using a simple standard DbContext and it looks like this:
public class TimetrackerDbContext : DbContext
{
public TimetrackerDbContext()
: base("name=DbConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
}
public virtual DbSet<MyEntity> MyEntities { get; set; }
}
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
Now in my App.config file I specify the connection string. I've been trying to use this connection:
<add name="DbConnection"
connectionString="User ID=xxx;Password=xxx;Host=xxx;Port=5432;Database=xxx;Pooling=true;"
providerName="System.Data.EntityClient" />
But when I run enable-migrations -contexttypename MyDbContext in the PM Console I get the following error:
Keyword not supported: 'user id'.
I tried specyfying the metadata, provider connection string but it also threw errors and it does not make much sense to use it in Code First. In case somebody it could be useful here's my whole 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.1" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<!--<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />-->
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<connectionStrings>
<add name="DbConnection"
connectionString="User ID=xxx;Password=xxx;Host=xxx;Port=5432;Database=xxx;Pooling=true;"
providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
The providerName of your connection string System.Data.EntityClient is for Database First (edmx) type connections where the actual provider is encoded in the connectionString value.
For Code First connections, the providerName should match the invariantName from the providers section. In your case, replace
providerName="System.Data.EntityClient"
to
providerName="Npgsql"

Set DatabaseInitializerForType in config file for Custom Initializer to fire

So I either get errors firing or nothing happens. I know that I have custom Entity Framework Initializer like this:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyEntity
{
public class EasyInitializer : DropCreateDatabaseAlways<EasyContext>
{
protected override void Seed(EasyContext context)
{
List<Person> persons = new List<Person>
{
new Person { FirstName = "Waz", LastName = "Amattau"},
new Person { FirstName = "Helena", LastName = "Handbasket"},
};
foreach (var person in persons)
context.Person.Add(person);
base.Seed(context);
}
}
}
I can call this when I set this quite easily:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyEntity
{
public class EasyContext : DbContext
{
public EasyContext() : base("name=EasyEntity")
{
Database.SetInitializer<EasyContext>(new EasyInitializer());
}
public DbSet<Person> Person { get; set; }
}
}
Yet this is all in a class library and when I have a console app to test this it will not fire in the app.config. I am ultimately looking to create builds or what not or apps to fire or not fire based on environment. After scouring the internet it seems many different people label and put different text in this config setting. I am using Entity Framework 6.1.3 according to NuGet, yet the config and references claim 6.0.0 and have wondered if this has changed and how to make it fire from a seperate project without having to hardcdoe the intializer to fire. I have this:
<appSettings>
<add key="DatabaseInitializerForType EasyEntity.EasyInitializer, EasyEntity" value="true" />
</appSettings>
I have tried setting 'value' to lots of things like 'Enabled', 'EasyEntity.EasyInitializer, EasyEntity', 'true', 'comeonpleasefire'. But nothing appears to work as I am ignorant of what to do. I saw another blog putting the setting inside the entityFramework node in the config section but that did not work either. My total config setting in my console app for reference:
<?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>
<appSettings>
<add key="DatabaseInitializerForType EasyEntity.EasyInitializer, EasyEntity" value="true" />
</appSettings>
<connectionStrings>
<add name="EasyEntity" providerName="System.Data.SqlClient" connectionString="Server=.;Database=Easy;Integrated Security=True;"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Entity Framework doesn't pick up values from the appSettings section of your application configuration file. Instead you need to use entityFramework.contexts.context.databaseInitializer section, something like this should do it:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
<contexts>
<context type="EasyEntity.EasyContext, EasyEntity">
<databaseInitializer type="EasyEntity.EasyInitializer, EasyEntity" />
</context>
</contexts>
</entityFramework>
EF does not run the initializer until you use the the context or explicitly tell EF to create the db.
Try this in you console application
using (var context = new EasyContext ())
{
// Uncomment this line to see the raw sql commands
//context.Database.Log = Console.WriteLine;
context.Database.CreateIfNotExists();
context.Database.Initialize(true);
}
To Answer the original question you can set the Initializer in the appSettings.
You can use reflection to set the Initializer like so:
<appSettings>
<add key="DatabaseInitializerForType EasyEntity.EasyContext, EasyEntity" value="System.Data.Entity.DropCreateDatabaseAlways`1[[EasyEntity.EasyContext, EasyEntity]], EntityFramework" />
You may have been confused by 'disabled' with the answer far different than setting it to 'enabled' or 'true'. If you want to run a 'seed' method you could use access the initializer class with the following.
<appSettings>
<add key="DatabaseInitializerForType EasyEntity.EasyContext, EasyEntity" value="EasyEntity.EasyInitializer, EasyEntity" />

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?

Categories

Resources