I have entity framework 5 with the mysql connector installed (mysql for vs 1.1.3 and mysql connector 6.8.3) and have a connection string in my app.config:
<add name="applicantDBEntities" connectionString="metadata=res://*/Models.applicantsDBModel.csdl|res://*/Models.applicantsDBModel.ssdl|res://*/Models.applicantsDBModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;user id=root;database=applicantsdb"" providerName="System.Data.EntityClient" />
If I use the connection string in the app.config, everything works, but I want the user to be able to choose his server, username, password and DB. How i tried to implement it:
public partial class applicantDBEntities : DbContext
{
public applicantDBEntities()
: base("name=applicantDBEntities")
{
}
public applicantDBEntities(string connectionString) : base (connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<applicant> applicants { get; set; }
public DbSet<file> files { get; set; }
}
And the initialization itself:
CONNECTION_PATTERN = "server={0};database={1};User Id={2};password={3}";
this.dbContext = new applicantDBEntities(String.Format(CONNECTION_PATTERN,
Settings.GetInstance().Server, Settings.GetInstance().Database,
Settings.GetInstance().User, Settings.GetInstance().Password));
but no matter what I pass as arguments (even wrong ones) I always end up in the OnModelCreating method.
What is the correct way to do this?
EDIT:
As #Andrew mentioned, my connection string was wrong. This is how I do it now:
string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*",
Provider = "MySql.Data.MySqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = Settings.GetInstance().Database,
DataSource = Settings.GetInstance().Server,
IntegratedSecurity = false,
UserID = Settings.GetInstance().User,
Password = Settings.GetInstance().Password
}.ConnectionString
}.ConnectionString;
this.dbContext = new applicantDBEntities(connectionString);
Your connection string is in invalid format.
It should resemble this:
"metadata=res://*/Northwind.csdl|
res://*/Northwind.ssdl|
res://*/Northwind.msl;
provider=System.Data.SqlClient;
provider connection string=
"Data Source=.\sqlexpress;
Initial Catalog=Northwind;
Integrated Security=True;
MultipleActiveResultSets=True""
and might be based on EntityConnectionStringBuilder
http://msdn.microsoft.com/en-us/data/jj592674.aspx here's description of how you should connect to database for different scenarios and framework versions
Related
I'm trying to figure out how to connect to an .mdf file using entityframework core. I found a resource on how to connect to one here However it doesn't seem to be working. I've made a var simple context using the Northwind dataset
public class Order
{
public int OrderId { get; set; }
public string CustomerID { get; set; }
public int EmployeeID { get; set; }
public DateTime OrderDate { get; set; }
// etc.
}
public class NorthwindContext : DbContext
{
public NorthwindContext(DbContextOptions options) : base(options) { }
public DbSet<Order> Orders { get; set; }
}
I've created a test class to attempt to connect to the DB
public string NorthwindConnectionString = #"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\source\Astoot\RestEzCore.Tests\TestDB\NORTHWND.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
[TestMethod]
public void TestMethod1()
{
var optionsBuilder = new DbContextOptionsBuilder<NorthwindContext>();
//I've also tried UseSqlLite()
optionsBuilder.UseSqlServer(this.NorthwindConnectionString);
using (var context = new NorthwindContext(optionsBuilder.Options))
{
var orders = context.Orders.ToList();
Assert.IsTrue(orders.Any());
}
}
However when I attempt to run my tests I get an error
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
Edit
I've also tried moving my MDF to users folder and connect using this connection string:
Data Source=(LocalDB)\MSSQLLocalDB;DataBase=Northwind;Integrated Security=True;Connect Timeout=30"
However this doesn't seem to work as well, it throws an exception
SqlException: Cannot open database "Northwind" requested by the login. The login failed.
Login failed for user 'MyUser'
Is there something wrong with my connection string?
I can't quite seem to figure out how to use an MDF with entityframework
I did some investigation, and it turns out that it was returning a bogus error because Northwind DB in built from SQL Server 2000, and I'm running SQL server 2016 so Instead I Created a Sample DB and used that as an MDF.
Now my connection string looks like so:
public static string MDF_Directory
{
get
{
var directoryPath = AppDomain.CurrentDomain.BaseDirectory;
return Path.GetFullPath(Path.Combine(directoryPath, "..//..//..//TestDB"));
}
}
public string astootConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB; " +
"AttachDbFilename="+ MDF_Directory + "\\Astoot.mdf;" +
" Integrated Security=True; Connect Timeout=30;";
Hi I have server with some databases that have the same schema. I use EF6 Database/Model First code and I do not want to create deterrent DbContext for them. for example my generated DbContext is :
public partial class TEST_Rev5_FINALEntities : DbContext
{
public TEST_Rev5_FINALEntities()
: base("name=TEST_Rev5_FINALEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Header> tbl_Headers { get; set; }
public virtual DbSet<Output> tbl_Output { get; set; }
public virtual DbSet<Run> tbl_Run { get; set; }
}
and I created a partial class to set the connection string
public partial class TEST_Rev5_FINALEntities : DbContext
{
public TEST_Rev5_FINALEntities(DbConnection dbConnection)
: base(dbConnection, true)
{
}
}
And I have the following method to create the connection with deterrent connection string:
public DbConnection GetConnectionString()
{
DbConnection conn;
SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = DataSource,
IntegratedSecurity = false,
UserID = User,
Password = Password,
MultipleActiveResultSets = true
};
SqlConnectionFactory sqlConnectionFactory = new SqlConnectionFactory(sqlConnectionStringBuilder.ConnectionString);
conn = sqlConnectionFactory.CreateConnection(DatabaseName);
return conn;
}
Finally I try to run it like this:
using (var context = new TEST_Rev5_FINALEntities(_dal.Connector.GetConnectionString()))
{
return context.tbl_Headers.FirstOrDefault();
}
but I get this error :
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException
HResult=0x80131509 Message=The context is being used in Code First
mode with code that was generated from an EDMX file for either
Database First or Model First development.
How can I do it?
The behavior EF uses depends on the way your connection string looks. If it includes a metadata attribute like this:
metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;
It will presume you are using Database or Model first development.
To make sure Code First is used, remove metadata part of the connection string.
I am trying to use register and login form in MVC4 . I have used Entity Framework from DB to create the model and now I want to generate the membership tables, but I have tried many things and I still can't access them.
I have 2 connection strings :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Projekti-20160917211151;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Projekti-20160917211151.mdf" providerName="System.Data.SqlClient" />
<add name="UniversitetiEntities" connectionString="metadata=res://*/Models.Universiteti.csdl|res://*/Models.Universiteti.ssdl|res://*/Models.Universiteti.msl;provider=System.Data.SqlClient;provider connection string="data source=ARBERS-PC\BERSANTA;initial catalog=Universiteti;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
In Account Model I changed the base in UniversitetiEntities :
public class UsersContext : DbContext
{
public UsersContext()
: base("UniversitetiEntities")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
I Also did this chang in InitializeSimpleMembershipAttribute file:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("UniversitetiEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
but it always throws this exception : The ASP.NET Simple Membership database could not be initialized.
AFAIK, SimpleMembershipProvider user profile management only works with SQL Server database connection string, not an EF connection string.
First, try setting your DB connection string instead of EF-generated connection string as stated here:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
// also set your DB connection string on current DB context
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
If the first solution won't work, try removing AttachDbFileName property from SQL Server connection string:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Projekti-20160917211151;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
NB: If your DB connection has certain user ID & password to get access, include them in DefaultConnection.
Depending on your EF model generation (code first, database first or model first approach), you can set autoCreateTables: by true or false based from existence of UserProfile table.
Further information: SimpleMembership Provider Reference
I am owndering about a way to create a ConnectionString on fly for SQLite and Entity Framework (MS VS2015, MS .NET Framework 4.5.6).
I mean the application gets some databases connectionstring and choose one of them.
Basically I would like to do it here
MyAppEntities context = new MyAppEntities();
The class itself looks like
public partial class MyAppEntities : DbContext
{
public MyAppEntities ()
: base("name=MyAppEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Commands> Commands { get; set; }
public virtual DbSet<Errors> Errors { get; set; }
}
Also I would like to know if possible to use relative path for SQLite here
<connectionStrings>
<add name="MyAppEntities " connectionString="metadata=res://*/DatabaseModel.AgentDataModel.csdl|res://*/DatabaseModel.AgentDataModel.ssdl|res://*/DatabaseModel.AgentDataModel.msl;provider=System.Data.SQLite.EF6;provider connection string="data source=D:\Databases\MyAgent.db""
providerName="System.Data.EntityClient" />
<add name="MyAppAgent.Properties.Settings.MyAppAgentConnectionString"
connectionString="data source=D:\Databases\MyAgent.db"
providerName="System.Data.SQLite.EF6" />
</connectionStrings>
Any clue how it can be done?
I am Using Entity Framework 5 Code-first approch. Here is my Context file :
using IMS.Domain.Inventory;
using IMS.Domain.Security;
using IMS.Domain.StoredProcedures;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IMS.Domain.DBContext
{
public class IMSDBContext : DbContext
{
public DbSet<ModuleAccounting> ModuleAccountings { get; set; }
public DbSet<ModuleInfo> ModuleInfos { get; set; }
public DbSet<ModuleType> ModuleTypes { get; set; }
public DbSet<UserAccounting> UserAccountings { get; set; }
public DbSet<UserGroup> UserGroups { get; set; }
public DbSet<UserInfo> UserInfos { get; set; }
//
// set a connection string
public IMSDBContext() // Constructor of the Context
{
this.Database.Connection.ConnectionString =
"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=IMSDB;Data Source=.\\SQLExpress";
}
}
}
Here I've added the connection string in the constructor. But is there any way to add the "Provider Name" to the connection string?
Is there a particular reason why you want to have the connection string hard coded in the db context. Normally it should be stored in the config file. You can specify the provider in the config file and refer the connection string from your context. That will solve your problem.
public MyDbContext()
: base("Name=MyDbContext")
{
}
And in your config file
<connectionStrings>
<add name="MyDbContext" connectionString="data source=.\sqlexpress;initial catalog=YourDbName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
</connectionStrings>
Yes: You can prepare a DbConnection type that can be passed to DbContext
which was built by the underlying provider and has the connection string built properly.
So to achieve this connection string in CODE... see below
<connectionStrings>
<add name="MyCTX" connectionString="Data Source=localhost;Initial Catalog=MYDB ;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
recall, that DBContext has an overloaded constructor
public DbContext(DbConnection existingConnection, bool contextOwnsConnection)
So you just need the Dbconnection built by the underlying factory provider.
See
public interface IDbConnectionFactory
which is implmented by these 3 types:
System.Data.Entity.Infrastructure.SqlCeConnectionFactory
System.Data.Entity.Infrastructure.LocalDbConnectionFactory
System.Data.Entity.Infrastructure.SqlConnectionFactory
So here is an example using SQLConnectionFactory. That returns a DBConnection.
Which can be passed to DBContext.
You can repeat/change or make variable at your programming leisure. For the other 2 providers.
public DbConnection GetSqlConn4DbName(string dataSource, string dbName) {
var sqlConnStringBuilder = new SqlConnectionStringBuilder();
sqlConnStringBuilder.DataSource = String.IsNullOrEmpty(dataSource) ? DefaultDataSource : dataSource;
sqlConnStringBuilder.IntegratedSecurity = true;
sqlConnStringBuilder.MultipleActiveResultSets = true;
// NOW MY PROVIDER FACTORY OF CHOICE, switch providers here
var sqlConnFact = new SqlConnectionFactory(sqlConnStringBuilder.ConnectionString);
var sqlConn = sqlConnFact.CreateConnection(dbName);
return sqlConn;
}