好的,我找到了答案,它有点复杂,所以我不确定我是否喜欢它。
要获得上面的表结构,您必须将 SystemUserAccount 创建为多对多。然后您需要在 SystemUserAccount 表的 UserId 列上创建一个单独的唯一 Key。我能找到运行它的唯一钩子是 DBInitializer 的 Seed 方法。这是代码:
public class SystemUser
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<SystemUserAccount> SystemUserAccounts{get;set;}
}
public class Account
{
public int Id { get; set; }
public ICollection<SystemUserAccount> SystemUserAccount { get; set; }
}
public class SystemUserAccount
{
public int UserId { get; set; }
public int AccountId { get; set; }
public virtual ICollection<AccountRole> AccountRoles { get; set; }
public SystemUser SystemUser { get; set; }
public Account UserAccount { get; set; }
}
public class AccountRole
{
public int Id { get; set; }
public String Name { get; set; }
public virtual ICollection<SystemUserAccount> UserAccounts { get; set; }
}
然后这个上下文:
public DbSet<SystemUser> SystemUser { get; set; }
public DbSet<SystemUserAccount> SystemUserAccount { get; set; }
public DbSet<Account> Account { get; set; }
public DbSet<AccountRole> AccountRole { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SystemUserAccount>()
.HasKey(sua => new { sua.UserId, sua.AccountId });
modelBuilder.Entity<SystemUserAccount>()
.HasRequired(sua => sua.SystemUser)
.WithMany(u => u.SystemUserAccounts)
.HasForeignKey(u => u.UserId);
modelBuilder.Entity<SystemUserAccount>()
.HasMany(sua => sua.AccountRoles)
.WithMany(ar => ar.UserAccounts)
.Map(m =>
{
m.ToTable("UserAccountRole");
m.MapLeftKey("UserId", "AccountId");
m.MapRightKey("AccountRoleId");
}
);
}
最后在数据库初始化程序的种子方法中:
public class DatabaseInitializer : DropCreateDatabaseAlways<PeopleContext>
{
protected override void Seed(PeopleContext context)
{
context.Database.ExecuteSqlCommand("ALTER TABLE SystemUserAccounts ADD CONSTRAINT uc_User UNIQUE(UserId)");
}
}
然后只需在程序中调用 DatabaseInitializer:
Database.SetInitializer<PeopleContext>(new DatabaseInitializer());
这给了我 OP 中显示的表结构。我不确定它在查询中的表现如何。
我希望它可以帮助任何试图这样做的人。
塔尔