在 MVC6 中扩展 Identity3

Extending Identity3 in MVC6

使用 asp.net5 的最新(当前)RC1 我正在考虑在 User 实体和 之间创建一个简单的关系工作日志 实体。

是否可以使用 Identity 中的 ApplicationUser Class 作为起点并使用定义为链接键的 ApplicationUser 键?我过去在扩展 ApplicationUser 时遇到过问题,因此生成了一个单独的 dbcontext(指向同一个数据库)并创建了我自己的管道以便将 IdentityUsers Id 传递到我单独的 dbcontext 中。有没有人有扩展 IdentityDbContext 添加外键表映射到 IdentityUser Class 的例子?

下面的例子

//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; }
    }

按照您的要求进行操作有望开箱即用。您可以查看 this commit 以了解新创建的具有标识的 MVC 6 项目与上面的架构之间的区别。

注册用户并刷新 /Home/Index 会导致按预期添加 WorkLogItem。请注意,您不需要单独的数据库上下文。

public IActionResult Index()
{
    var user = _db.Users.Include(p => p.WorkLogItems).FirstOrDefault();
    if (user != null)
    {
        user.WorkLogItems.Add(new WorkLogItem { Description = "New item added" });
        _db.SaveChanges();
        ViewBag.WorkItems = user.WorkLogItems.ToList();
    }
    else ViewBag.WorkItems = new WorkLogItem[] { };

    return View();
}

将任何集合添加到现有实体时需要注意的关键事项是;

  1. 确保添加迁移并更新数据库
  2. 确保在查询中使用 Include 因为 EF7 does not support Lazy Loading.