SQLite with Entity Framework [duplicate] - c#

This question already has answers here:
Unable to find the requested .Net Framework Data Provider - SQLite
(2 answers)
Closed 8 years ago.
I can't configurate App.config. I have error
base {"Unable to determine the provider name for provider factory of type 'System.Data.SQLite.SQLiteFactory'. Make sure that the ADO.NET provider is installed or registered in the application config."} System.SystemException {System.NotSupportedException}
My code:
class Program
{
static void Main(string[] args)
{
new Program();
}
public Program()
{
CustomerContext cc = new CustomerContext();
cc.Customers.Add(new Customer() { Name = "sdf", LastName = "dfs" });
}
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public class CustomerContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
And 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>
<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="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite" />
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6"
description=".Net Framework Data Provider for SQLite (Entity Framework 6)"
type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="CustomerContext" connectionString="Data Source=test.sqlite" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
</configuration>
File test.sqlite is added to project also EF and SQLite are added by nuget

Comment out the following:
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
Also, is Entity Framework (edmx file) defined within your Application project or is it defined within a separate class library?
If it is in a separate class library, then copy the xml within your app config file of your class library project into the app config file of your app project.
Update:
Last time I checked, SQLite must be defined within your app project and NOT a separate class library.

Related

Why is my connection string not found, when I am referencing the project where it exists [duplicate]

This question already has answers here:
Connection String in app.config of a dll
(2 answers)
Closed 5 years ago.
I have built a separate data layer which contains my Entity Framework. I made a reference to this separate project in my current project ... I added the following to my current MVC controller:
using SMCD_DataLayer;
[HttpPost]
public ActionResult Login(LoginViewModel lv)
{
var db = new SMCD_DataStoreEntities();
var found = db.Users.Select(x => x.Username == lv.userId && x.Password == lv.passWord).Any();
if (ModelState.IsValid)
{
if (!found)
{
lv.errorMsg = "User ID is invalid!";
}
else
{
return RedirectToAction("IntroPage", "Devices");
}
}
return View(lv);
}
my SMCD_DataStoreEntities lives in SMCD_DataLayer, but this controller lives in SMCD_Portal Project.
on the line var found ... I am getting the following error message:
System.InvalidOperationException occurred
HResult=0x80131509
Message=No connection string named 'SMCD_DataStoreEntities' could be found in the application config file.
The connection string lives in the SMCD_Datalayer, even though I am referencing it in my current project, does it need to live in the SMCD_Portal Project?
This is the connection string which lives in the App.config in the SMCD_DataLayer, remember my controller lives in SMCD_Portal
<?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.6.1" />
</startup>
<connectionStrings>
<add name="SMCD_DataStoreEntities" connectionString="metadata="res://*/SMCD DataStore.csdl|res://*/SMCD DataStore.ssdl|res://*/SMCD DataStore.msl";provider=System.Data.SqlClient;provider connection string="data source=KARL-LT\SQLEXPRESS;initial catalog=SMCD_DataStore;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>
Any .config settings that are used by your application, or used by any referenced assemblies, will generally need to be in the main application's .config file.
The same applies for connection strings.
So put those connection strings in your main application's .config file and you should be alright.

SQL Server connection throw exception when using Entity Framework migration - add code snippet

I have a simple C# solution which has an entity class and a context class and also a console application which I use to test Entity Framework migration. But I always get this error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified).
Here is the connection string in the app.config (I put it in both console's app.config and context class's app.config):
<add name="ZzaDbConnectionString"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite‌​;MultiSubnetFailover=False"
providerName="System.Data.SqlClient" />
I copied the connection string from "Connection string" property of the database from SQL Server ObjectExplorer so I suppose it is good.
Any suggestion why it always throws this exception?
I added entity class, context class and console class and hope this will have some clarification on my questions.
This is Entity class.
namespace Zza.Entities
{
public class Customer
{
public Guid Id { get; set; }
[MaxLength(50)]
public string FullName { get; set; }
}
}
This is Context class:
namespace Zza.Data
{
public class ZzaDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
}
This is console class:
namespace TestEFMigration
{
public class Program
{
static void Main(string[] args)
{
CreateDataBase();
}
private static void CreateDataBase()
{
var context = new ZzaDbContext();
context.Database.Initialize(false);
}
}
}
Console's 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 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ZzaDbConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
And app.config of context class:
<?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>
<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="ZzaDbConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Thanks.
I reduced connection strings.
As you are using localdb, it may have trouble with some of your parameters intended for full sql server (are you aware of it?)
Differences I found are:
connectionString="AttachDbFilename=|DataDirectory|\Zza.mdf;MultipleActiveResultSets=True;App=EntityFramework"
connectionString="Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite‌​;MultiSubnetFailover=False"
So, please try removing all options on second line and adding ones on top (AttachDbFilename can be a path to the mdf you want to use/create)
<add name="ZzaDbConnectionString"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;
AttachDbFilename=|DataDirectory|\Zza.mdf;MultipleActiveResultSets=True;App=EntityFramework;"
providerName="System.Data.SqlClient" />
EDIT: Ceck this
public class ZzaDbContext: DbContext
{
public ZzaDbContext()
: this("ZzaDbConnectionString")
{
}
// ...

MySql EF6 with IdentityDbContext

I try to use MS Identity with an MySql Databse and Code-First.
My DbContext Class:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class TestDbContext : IdentityDbContext<ApplicationUser>
{
public TestDbContext()
{
}
public TestDbContext(string cnString)
: base(cnString)
{
}
}
My App Config:
<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="TestDbContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=test;uid=root;password=root"/>
</connectionStrings>
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
</defaultConnectionFactory>
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</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.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>
If i use the normal DbContext its works with Code-First Migrations. But if i change to IdentityDbContext and i try to "Update-Database" i get the following Error:
Failed to set Database.DefaultConnectionFactory to an instance of the
'System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
EntityFramework' type as specified in the application configuration.
See inner exception for details.
How can i get MS Identity to work with MySql?
Ok i have change the DefaultConnectionFactory to
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
but now i get another Error:
Format of the initialization string does not conform to specification starting at index 0.
Ok i get the Database Connection to work but the Identity Tables such as aspnetuser won't create automaticly.

SQLite: Entity Framework 6 - Wrong DbProviderFactory

I'm going bonkers with this.
I have a standard C# console application, with EF 6.1.3 and SQLite 1.0.97.0. I've set up my app.config to connect to the SQLite database using standard ADO, which works:
static void StandardConnection()
{
try
{
SQLiteConnection db = new SQLiteConnection(ConfigurationManager.ConnectionStrings["StudioContext"].ConnectionString);
db.Open();
Console.WriteLine("Connected");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
But for the love of me, I can't get EF to connect to this database. I have tried every single solution I could read up on, but every time I try to connect, I find the DBProviderFactory always points to {System.Data.SqlClient.SqlClientFactory}. It is driving me insane.
Following, my DbContext class:
public class SqliteContext: DbContext
{
public SqliteContext()
: base(ConfigurationManager.ConnectionStrings["StudioContext"].ConnectionString)
{
Database.SetInitializer<SqliteContext>(null);
}
}
I don't want code first enabled, so disabled it here as this is off an existing application, being ported from PHP to C# and we have to work with the database as it is currently.
The code that's trying to connect:
static void EntityFrameworkConnection()
{
try
{
using (var db = new SqliteContext())
{
if (db.Database.Connection.State == System.Data.ConnectionState.Closed)
{
db.Database.Connection.Open();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Very basic, open an instance of the context, check the state and connect if closed, this step is not required as I understand that EF will open the connection, if closed, when doing something like a save, for example, I'm just trying to get the DB to connect.
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>
<connectionStrings>
<add name="StudioContext" connectionString="Data Source=.\studio.db" providerName="System.Data.SQLite" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6, Version=1.0.97.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6, Version=1.0.97.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.97.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6, Version=1.0.97.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
</DbProviderFactories>
</system.data>

Facing issue in connecting oracle with entity frameowrk

I am using Oracle 11g and Entity Framework 6 versions.
I am facing the following error:
"An error occurred while getting provider information from the
database. This can be caused by Entity Framework using an incorrect
connection string. Check the inner exceptions for details and ensure
that the connection string is correct."
My App.Config is as follows:
<?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"/>
<section name="oracle.manageddataaccess.client"
type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<connectionStrings>
<clear/>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client"
connectionString=" Data Source=HRFOLATEST1;User ID=hrms2;Password=hrms2;"/>
</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="Oracle.ManagedDataAccess.Client"
type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.ManagedDataAccess.Client"/>
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver"
type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<publisherPolicy apply="no"/>
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral"/>
<bindingRedirect oldVersion="4.121.0.0 - 4.65535.65535.65535" newVersion="4.121.2.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
My Db Context:
class DatabaseContext : DbContext
{
public DatabaseContext() : base("OracleDbContext")
{
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure domain classes using modelBuilder here
modelBuilder.Entity<User>().ToTable("HRMS_OLAS_TREE");
modelBuilder.Entity<User>().Property(user => user.ID).HasColumnName("EMP_ID").HasColumnType("VARCHAR");
modelBuilder.Entity<User>().Property(user => user.NAME).HasColumnName("EMP_NAME").HasColumnType("VARCHAR");
base.OnModelCreating(modelBuilder);
}
}
internal class User
{
public long ID { get; set; }
public string NAME { get; set; }
}
Please let me now what mistake i am doing.
I have changed the connection string to the following and it started working:
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client"
connectionString=" Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname)(PORT=yourportnumber))(CONNECT_DATA=(SERVICE_NAME=""servicename))); User Id=xxx;Password=xxxx;"/>
we can find these details in tnsnames.ora file.
In Db Context add the following code:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema("yourschemaName");
modelBuilder.Configurations.Add(new EmployeeMapper());
}

Categories