提到DbContext,对于经常使用DbFirst模式的开发者来说已经再熟悉不过了,EntityFramework全靠这员大将。它的作用是代表与数据库连接的会话,提供了查询、状态跟踪、保存等功能。
还有一个重要的对象是DbSet,对实体类型提供了集合操作,比如Add、Attach、Remove。继承了DbQuery,所以可以提供查询功能。
ActDbContext.cs示例
using Microsoft.EntityFrameworkCore;
using Rdf.Domain.Entities.Act;
namespace Rdf.EntityFrameworkCore
{
public class ActDbContext : DbContext
{
public ActDbContext(DbContextOptions<ActDbContext> options)
: base(options)
{
}
#region Act
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<OrganizationUnit> OrganizationUnits { get; set; }
public DbSet<Module> Modules { get; set; }
public DbSet<Function> Functions { get; set; }
public DbSet<Edition> Editions { get; set; }
public DbSet<Tenant> Tenants { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<RoleModule> RoleModules { get; set; }
public DbSet<ModuleFunction> ModuleFunctions { get; set; }
public DbSet<UserOrganizationUnit> UserOrganizationUnits { get; set; }
#endregion
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Role>().ToTable("Act_Role");
builder.Entity<Role>().HasKey(k => k.Id);
builder.Entity<Role>().Property(t => t.Id).HasColumnName("RoleId");
base.OnModelCreating(builder);
}
}
}
说明:DbContext 需要引用 Microsoft.EntityFrameworkCore
增加对EF的支持
我们打开Startup.cs修改ConfigureServices(IServiceCollection services)方法,增加对EF的支持
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
// 增加对EF的支持
services.AddDbContext<ActDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));
services.AddMvc();
}
上面的SqlServerConnection是我们的数据库连接字符串,它的配置在project.json文件中:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"SqlServerConnection": "Server=.;Database=RdfDb;User ID=sa;Password=sh.123456;"
}
}
这样,实际上我们就完成了,但是我们后面会用到,我们目前不操作数据。