We have an existing .NET Framework library with Entity Framework 6 and static methods like this:
public class OrderManager
{
public static OrderDTO GetOrderByOrderId(int oid)
{
var entities = new MyEntities();
....
}
}
where MyEntities have a hardcoded connectionstring name
internal partial class MyEntities : DbContext
{
public SSE3Entities() : base("name=MyEntities") {}
}
When used in a ASP.NET application, the web.config have a connectionstrings defined like this:
<connectionStrings>
<add name="MyEntities" connectionString="metadata=res://*/M..." providerName="System.Data.EntityClient" />
</connectionStrings>
But how can I reuse this library in a aspnet core application. Tried:
{
"ConnectionStrings": {
"MyEnties": "metadata=res://*/M...",
},
"Logging": {
...
}
}
I know passing the connectionstring into the OrderManager constructor is what we should have done years ago, but changing it now requiers a lot of work.
Are there any ways we can make EF read the new configurations system?
Or could we maybe write some settings to the old ConfigurationManager?
I tried dropping in a web.config without any luck
add System.Configuration.ConfigurationManager from nuget
add a file app.config
.net core applictaion is a consle app, so it find app.config first
app.config:
<appSettings>
<add key="webpages:Version" value="2.0.0.0"/>
</appSettings>
This solution will work for ASPNET Core MVC 2.0, 2.2 and 3.0 In your app root go find the appsetting.json file and modify the connection string.
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=DESKTOP-3R4MR9H\\SQLSERVER3R4MR9;Initial
Catalog=ASPNetCoreMVC;Persist Security Info=True;User
ID=sa;Password=********;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Related
I have an Azure Function that uses database first approach connection string. The connection string is located in the local.settings.json file, which contains the sensitive data.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true"
},
"ConnectionStrings": {
"MyConnectionString": "data source=localhost\\sqlexpress;initial catalog=SampleQrCodes;user id=sa;password=****;MultipleActiveResultSets=True;App=EntityFramework"
}
}
If I try removing providerName it gives me the following exception:
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. This will not work correctly.....you pass it to one of the base DbContext constructors that take a DbConnection
Actual connection string (generated from EF):
<add name="DataContext" connectionString="metadata=res://*/EFModel.csdl|res://*/EFModel.ssdl|res://*/EFModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\sqlexpress;initial catalog=SampleQrCodes;user id=sa;password=***;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Here is similar question Load Connection String from Config File in Azure Functions but it is not working for me how to define this connection string in local.settings.json via database first approach?
According to your description, here is the similar git hub issue. Per my test, you could configure your connection string within the local.settings.json file as follows:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=<account-name>;AccountKey=<account-key>",
"AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=<account-name>;AccountKey=<account-key>"
},
"ConnectionStrings": {
"DataContext": {
"ConnectionString": "metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='data source=<server-name>.database.windows.net;initial catalog=<database-name>;persist security info=True;user id=<username>;password=<password>;MultipleActiveResultSets=True;App=EntityFramework'",
"ProviderName": "System.Data.EntityClient"
}
}
}
For deploying to your azure function, you may need to modify your DbContext. More details, you could refer to this similar issue.
Is there a way how to specify which DataProvider(SQL Server) and ConnectionString to use just for generating a migrations(Add-Migration) and updating a database(Update-Database)? I do not want to hardcode the data provider selection and connection string loading into DbContext (.UseSqlServer()).
I think EF6 can pick a connection string directly from web.config, is there something similar in EF7?
No you have to use optionsBuilder:
example:
string oldConnectionString =#"Server = .\;Initial Catalog=EFTutorial; AttachDbFilename=|DataDirectory|\EFTutorial.mdf; Trusted_Connection = True; MultipleActiveResultSets = true";
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(oldConnectionString );
base.OnConfiguring(optionsBuilder);
}
you can also load as json and load it directly from app.config or web.config.
If you are using .Net Core:
you can define in your appsettings.json the conenction string as following:
{
{
....
},
"Data": {
"ConnectionString": "..."
}
}
on App starting you have to load it:
// Set up configuration sources.
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
builder.AddEnvironmentVariables();
Configuration = builder.Build().ReloadOnChanged("appsettings.json");
After that you also have to configure Entity Framework in Startup.cs.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<AppContext>(options =>
{
options.UseSqlServer(Configuration "Data:ConnectionString"]); });
services.AddScoped<AppContext, AppContext>();
...
}
}
The improtant thing here:
services.AddScoped((_) => new AppContext(Configuration["Data:DefaultConnection:ConnectionString"]));
https://docs.asp.net/en/latest/data/entity-framework-6.html
Examples to conenction string in Entity Framework Core 1.0 / 7:
https://docs.asp.net/en/latest/fundamentals/configuration.html
The old way(You can do that also with EF Core) we have load the conenctionString from App.config or web.config
and by the Migration process Add-Migration/Update-Database, EF will automatically found the Connection string.
But you can also provide the conenction string to Add-Migration in the NuGet comamnd line as parameter.
I hope this will solve your Problem!
i am building an restaurent reservation system , using asp.net mvc 4 entityframework, unity (for Ioc) and unit of work , repository pattern. So i make 4 project to the solution on vs 2013 :
RestaurentSyeteme (Web project ASP.NET MVC 4)
RestaurentSystemeBusiness : i put business logic in this layer
RestaurentSystemeDAL : Data access , entityFramework, repositories and context
RestaurentSystemeDomain : my entities
here is the code for my dbContext :
public class RestaurentDbSystem : UnitOfWork
{
public RestaurentDbSystem(string nameOrConnStr)
: base(nameOrConnStr)
{
}
}
and here the UnitOfWork :
public class UnitOfWork : DbContext, IUnitOfWork
{
public UnitOfWork(string nameOrConnString)
: base(nameOrConnString)
{
}
}
here is the code to configure my container (Unity) :
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
container.RegisterType<IUnitOfWork, RestaurentDbSystem>(new PerHttpRequestLifetime(),
new InjectionConstructor("RestaurentDbSystem"));
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IClientService, ClientService>();
container.RegisterType<IClientRepository, ClientRepository>();
container.RegisterType<IRepository<User>, Repository<User>>();
container.RegisterType<IRepository<UserType>, Repository<UserType>>();
return container;
}
and here what i put on my web.config to config connectionstring
<add name="RestaurentDbSystem"
connectionString="Data Source=LMA000049\mssqlserver;
Initial Catalog=RestaurentSystemDb;Integrated Security=true"
providerName="System.Data.SqlClient" />
I have created database with the name ='RestaurentSystemDb'.
The problme is when a execute the app i have this exception :
An exception of type 'System.Data.ProviderIncompatibleException' occurred in EntityFramework.dll but was not handled in user code
RestaurentDbSystem in public class RestaurentDbSystem : UnitOfWork
RestaurentSystemDb in Initial Catalog=RestaurentSystemDb
I think those two must be match.
Normally, if they are not same, Code-First tries to create a database on SQL Express.
I have created a database using EF code-first like there http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-code-first-walkthrough.aspx. But when I input data to db by add() and then call savechanges() I don't see new database in SQL Server databases folder and there no exceptions. Is it right? Where can I find my database and how to put it in databases folder?
I work with this code:
public class Name
{
public long NameId { get; set; }
public string FullName { get; set; }
}
public class InfoContext : DbContext
{
public DbSet<Name> Names { get; set; }
}
Then I call it:
var db = new InfoContext();
var Names = new Name
{
NameId = 1,
FullName = "test"
};
db.Names.Add(Name);
db.SaveChanges();
var test = db.Names.Find(1);//there I get correct value
I have connectionString in web.config like this:
<connectionStrings>
<add name="InfoName" providerName="System.Data.SqlClient"
connectionString="Server = .\MYINSTANCE; Initial Catalog=mydbname;" />
</connectionStrings>
Based on your comments you need to modify the web.config file in your project root (not the one in your Views folder. In there you can add a section as follows:
<connectionStrings>
<add name="EFDbContext" connectionString="Data Source = .; Initial Catalog = ITSDB; Integrated Security = true" providerName="System.Data.SqlClient"/>
</connectionStrings>
The name property of the element is the DbContext name of your Data model, so if your class is defined as:
public class SomeContext : DbContext
{
...
}
Then your config should be:
<connectionStrings>
<add name="SomeContext" connectionString="Data Source = .; Initial Catalog = ITSDB; Integrated Security = true" providerName="System.Data.SqlClient"/>
</connectionStrings>
As for the connection string, its dependent on your database.
Check the defaultConnectionFactory type in your config. I expect it is set to LocalConnectionFactory, as this seems to be default.
Change it to the following and your SQL instance will be used.
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.; Integrated Security=True; MultipleActiveResultSets=True;" />
</parameters>
</defaultConnectionFactory>
Your DB should appear in SQL Management Studio (SQLMS) with a name that matches the namespace and DbContext.
Or you can just put in "Data Source = " value your server's name which selected in you SQL Management Studio.
<connectionStrings>
<add name="SomeContext" connectionString="Data Source = **Server'sName**; Initial Catalog = ITSDB; Integrated Security = true" providerName="System.Data.SqlClient"/>
I am trying to incorporate 'EF Tracing Data Provider' into an existing MVC2 app using VS2010, .NET 4.0 in order to log all SQL commands. I have no interest at this time in the caching provider. I beleive I have followed all the steps listed in the blog posting. BLOG POST My project does compile without error, however when I attempt to run the project I get the following error:
'String cannot have zero length.' The error points to Extended_JCIMS_MVC2_EF_Entities.cs Line: 25
Line 25: public ExtendedJCIMS_DevEntities(string connectionString)
Line 26: :base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
I am unable to determine what is causing this error. I assume the error is referring to the connection string from the Web.Config file. It does not like the 'connectionString' variable. I'm obviously doing something worng. I would appreciate a push in the right direction.
The relevant bits are as follows:
Web.config
--------------------------------------------------------------------------
<add name="JCIMS_DevEntities"
connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial Catalog=MyDatabase;User ID=MyUser;Password=myPassWord;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient"/>
<system.data>
<DbProviderFactories>
<add name="EF Tracing Data Provider" invariant="EFTracingProvider" description="Tracing Provider Wrapper"
type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
<add name="EF Generic Provider Wrapper" invariant="EFProviderWrapper" description="Generic Provider Wrapper"
type="EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
</DbProviderFactories>
</system.data>
Global.ascx
-----------------------------------------------------------------------
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
//EFTracingProviderConfiguration - LOG ALL Sql commands
EFTracingProviderConfiguration.LogToFile = Server.MapPath("~/JCIMS_MVC2_EF_SQL_Logfie.txt");
}
Extended_JCIMS_MVC2_EF_Entities.cs
--------------------------------------------------------------------------
namespace JCIMS_MVC2_EF.DomainModel
{
/// <summary>
/// Partial calss that Extends the EF Datacontext Class
/// </summary>
public partial class ExtendedJCIMS_DevEntities : JCIMS_DevEntities
{
private TextWriter logOutput;
public ExtendedJCIMS_DevEntities()
: this("name=JCIMS_DevEntities")
{
}
public ExtendedJCIMS_DevEntities(string connectionString)
: base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
connectionString,
"EFTracingProvider"
))
{
}
//... and more
}
}
SearchRepository.cs
------------------------------------------------------------------
public class SQLSearchRepository : ISearchRepository
{
//Database connection
private ExtendedJCIMS_DevEntities db = new ExtendedJCIMS_DevEntities(); // tracing version
public IEnumerable<SearchResults> ListAll(string strSearch, string chkSearch)
{
return (from s in db.Schools....
// and more...
}
Appreciate any assistance anyone can give me...
Have you debugged and confirmed that the connectionString passed into the ExtendedJCIMS_DevEntities method is not null or empty? That's what the error seems to indicate.