[英]How to configure Entity Framework 6 for ASP.net Core
I'm trying to configure a new project to use Entity Framework 6
with ASP.net Core
, I'm using the full .net
framework in order to be able to use Entity Framework 6
. 我正在尝试配置一个新项目以使用带有ASP.net Core
Entity Framework 6
,我正在使用完整的.net
框架以便能够使用Entity Framework 6
。 This is a project that was in MVC before and I need to migrate it to Core. 这是之前在MVC中的项目,我需要将其迁移到Core。 This is what I've done(I have two projects, one Asp.net Core
and a class library
that contains some classes and the DBContext class
): 这是我做了什么(我有两个项目,一个Asp.net Core
和class library
包含一些类和DBContext class
):
appsettings.json
: appsettings.json
:
"Data": {
"ConnectionStrings": {
"MyConnection": "Server=namedatabase.database.secure.windows.net,1433;Database=database_Name;User ID=blahblah;Password=blahblah;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<MyDBContext>(_ => new LIGDataContext(Configuration.GetConnectionString("MyConnection")));
}
I have the DBContext
class separated in a class library(.dll)
: 我在class library(.dll)
分隔了DBContext
类:
public class MyDBContext: DbContext
{
public MyDBContext(string connString): base(connString)
{
}
But I have this code inside some controllers of my asp.net Core
project and I'm not sure how to refer now to the DBContext
instance... Clearly is asking for the connString
parameter, this is the first time I'm doing this and I'm not sure which is the best approach to do this, ConfigurationManager
is not available anymore in Core
what do I need to do? 但我在我的asp.net Core
项目的某些控制器中有这个代码,我不知道现在如何引用DBContext
实例......显然是要求connString
参数,这是我第一次这样做我不确定哪种方法最好,在Core
不再提供ConfigurationManager
我需要做什么? This is Entity Framework 6 no Entity Framework Core.. 这是实体框架6没有实体框架核心..
public class MyController : Controller
{
public ActionResult MyAction()
{
var _ctx = new MyDBContext();
return PartialView(_ctx.FormsiteApplications.Where(f => f.Application).OrderBy(f => f.Title).ToList());
}
dime2lo is right, you can inject the DbContext to the controller. dime2lo是对的,你可以将DbContext注入控制器。
codepublic class StoreController : Controller
{
private DefaultDbContext _dbContext = null;
public StoreController(DefaultDbContext dbContext)
{
this._dbContext = dbContext;
//Do something with this._dbContext ...
}
}
or create a context factory 或创建一个上下文工厂
public class DefaultDbContextFactory : IDbContextFactory<DefaultDbContext>{
public DefaultDbContext Create()
{
return new DefaultDbContext("Server=XXXX ;Database=XXXXX;Trusted_Connection=True;");
}
Reference : Getting Started with ASP.NET Core and Entity Framework 6 参考:ASP.NET核心和实体框架入门6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.