c# - EntityFramework 6 Code-based configuration of connection string for database-first -
i'm attempting make existing application without app.config (it required due specific environment). problem it's heavily relying on entityframework 6 work sql-server.
i'm trying utilize of code-based configuration can't figuar out how provide correct connection string through configuration.
i've made configuration class:
public class myconfiguration : dbconfiguration { public myconfiguration() { setdefaultconnectionfactory(new myconnectionfactory()); setproviderservices("system.data.sqlclient", system.data.entity.sqlserver.sqlproviderservices.instance); } }
then providing dbcontext (generated ef automaticaly bd):
[dbconfigurationtype(typeof(myconfiguration))] public partial class testmodelentities { }
with custom connection factory:
public class myconnectionfactory : idbconnectionfactory { public dbconnection createconnection(string nameorconnectionstring) { var newconnstringbuilder = new sqlconnectionstringbuilder { userid = "user", password = "pass", initialcatalog = "databasename", datasource = "servername" }; var entityconnectionbuilder = new entityconnectionstringbuilder { provider = "system.data.sqlclient", providerconnectionstring = newconnstringbuilder.tostring(), metadata = @"res://*/testmodel.csdl| res://*/testmodel.ssdl| res://*/testmodel.msl" }; var newdbconnect = new entityconnection(entityconnectionbuilder.tostring()); return newdbconnect; } }
however. when i'm trying test it, i'm still getting unintentionalcodefirstexception
. why? missing?
you should provide connection string context via :base(connectionstring). create class below:
public class connectionstringbuilder { public static string construct() { var newconnstringbuilder = new sqlconnectionstringbuilder { userid = "user", password = "pass", initialcatalog = "databasename", datasource = "servername" }; var entityconnectionbuilder = new entityconnectionstringbuilder { provider = "system.data.sqlclient", providerconnectionstring = newconnstringbuilder.tostring(), metadata = @"res://*/testmodel.csdl| res://*/testmodel.ssdl| res://*/testmodel.msl" }; return entityconnectionbuilder.tostring(); } }
then modify context constructor this:
public dbcontext() : base(connectionstringbuilder.construct()) { }
it should work fine now. (source)
Comments
Post a Comment