使用asp.net5的最新(当前)RC1我正在寻找在 User 实体和 WorkLog 实体之间创建一个简单的关系 .
是否可以使用Identity中的ApplicationUser类作为起点并使用定义为链接键的ApplicationUser键?我在过去扩展ApplicationUser时遇到了问题,因此生成了一个单独的dbcontext(指向同一个数据库)并创建了我自己的管道,以便将IdentityUsers Id传递给我的单独dbcontext . 有没有人有任何扩展IdentityDbContext添加外键表映射到IdentityUser类的示例?
以下示例
//DBContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<WorkLogItem> WorkLogItems { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<WorkLogItem>(
e =>
{
e.Property(p => p.id).IsRequired().UseSqlServerIdentityColumn();
});
}
}
//WorkLogItem
public class WorkLogItem
{
public int id { get; set;}
public String UserId { get; set; }
public int Hours { get; set; }
public String Description { get; set; }
}
//ApplicationUser
public class ApplicationUser : IdentityUser
{
public ICollection<WorkLogItem> WorkLogItems { get; set; }
}
1 回答
做你想问的东西应该是开箱即用的 . 您可以查看this commit以查看新创建的带有Identity的MVC 6项目与上面的架构之间的区别 .
注册用户和刷新/ Home / Index会导致
WorkLogItem
按预期添加 . 请注意,您不需要单独的DB上下文 .将任何集合添加到现有实体时要注意的关键事项是:
确保添加迁移并更新数据库
确保在查询中使用
Include
,因为EF7 does not support Lazy Loading .