开始之前,请确保在 project.json 中针对完整的 .NET Framework 进行编译,因为 Entity Framework 6 不支持 .NET Core。如果您需要跨平台功能,则需要升级到 Entity Framework Core。
在您的 project.json 文件中为完整的 .NET Framework 指定一个目标:
"frameworks": {
"net46": {}
}
然后设置连接字符串和依赖注入
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
}
在 ConfigureServices 的 Startup 类中,添加上下文的工厂方法及其连接字符串。上下文应在每个范围内解析一次,以确保性能并确保实体框架的可靠运行。
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped((_) => new ApplicationDbContext(Configuration["Data:DefaultConnection:ConnectionString"]));
// Configure remaining services
}
ntity Framework 6 允许在 xml(在 web.config 或 app.config 中)或通过代码指定配置。从 ASP.NET Core 开始,所有配置都是基于代码的。
基于代码的配置是通过创建System.Data.Entity.Config.DbConfiguration 的子类并将System.Data.Entity.DbConfigurationTypeAttribute 应用到您的DbContext 子类来实现的。
我们的配置文件通常如下所示:
<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>
defaultConnectionFactory 元素设置连接的工厂。如果未设置此属性,则默认值为 SqlConnectionProvider。另一方面,如果提供了值,则给定类将用于使用其 CreateConnection 方法创建 DbConnection。如果给定的工厂没有默认构造函数,那么您必须添加用于构造对象的参数
[DbConfigurationType(typeof(CodeConfig))] // point to the class that inherit from DbConfiguration
public class ApplicationDbContext : DbContext
{
[...]
}
public class CodeConfig : DbConfiguration
{
public CodeConfig()
{
SetProviderServices("System.Data.SqlClient",
System.Data.Entity.SqlServer.SqlProviderServices.Instance);
}
}
本文将向您展示如何在 ASP.NET Core 应用程序中使用 Entity Framework 6。
https://docs.asp.net/en/latest/data/entity-framework-6.html