实体框架-如何创建具有两个继承索引的链接表
本文关键字:两个 继承 索引 链接表 何创建 框架 实体 创建 | 更新日期: 2024-09-26 00:20:12
我使用的是EntityFramework和ASP。NET标识。我从IdentityUser和IdentityGroup派生,为我的应用程序存储额外的字段。
我想调用属性:User。组和组。用户,多对多关系,并具有EntityFramework自动创建的链接表GroupUsers。
我的第一次尝试如下:
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
public virtual ICollection<ApplicationGroup> Groups { get; set; }
// ...
}
public class ApplicationGroup : IdentityGroup<ApplicationUser>
{
public virtual ICollection<ApplicationGroupRole> Roles { get; set; }
}
public class IdentityGroup<TUser, TKey> : IGroup<TKey>
where TUser : IdentityUser
where TKey : IEquatable<TKey>
{
public virtual ICollection<TUser> Users { get; set; }
// ...
}
DBMigration看起来有点像
CreateTable(
"UMS.ApplicationGroupApplicationUsers",
c => new
{
ApplicationGroup_Id = c.String(nullable: false, maxLength: 128),
ApplicationUser_Id = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.ApplicationGroup_Id, t.ApplicationUser_Id })
.ForeignKey("UMS.ApplicationGroups", t => t.ApplicationGroup_Id, cascadeDelete: true)
.ForeignKey("UMS.Users", t => t.ApplicationUser_Id, cascadeDelete: true)
.Index(t => t.ApplicationGroup_Id)
.Index(t => t.ApplicationUser_Id);
特别要注意的是,链接表有两个索引,每个外键一个索引。
但是,我想显式地命名链接表,所以在DBContext中添加了:
modelBuilder.Entity<ApplicationUser>().ToTable("Users");
modelBuilder.Entity<ApplicationGroup>().ToTable("Groups")
.HasMany(x => x.Users)
.WithMany(x => x.Groups)
.Map(x =>
{
x.ToTable("GroupUsers");
x.MapLeftKey("UserId");
x.MapRightKey("GroupId");
});
然而,这给了我一个只有1个索引的自动迁移:
CreateTable(
"UMS.GroupUsers",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
GroupId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.GroupId })
.ForeignKey("UMS.Groups", t => t.UserId, cascadeDelete: true)
.ForeignKey("UMS.Users", t => t.GroupId, cascadeDelete: true)
.Index(t => t.UserId);
这只是EntityFramework中的一个错误吗?只有当一个类型通过派生类型具有另一个类型的集合时,才会出现这种情况。是否可以在自动创建两个索引的同时保留一个显式命名的链接表?
这可能无法解决您遇到的问题,但它会更正您的代码。在您的情况下,根据定义,"左键"应该是"GroupId","右键"应该为"UserId"。检查此链接。注意你发布的代码,你已经混合了它们:
ForeignKey("UMS.Groups",t=>t.UserId,cascadeDelete:true).ForeignKey("UMS.Users",t=>t.GroupId,cascadeDelete:true)
你的代码应该是这样的:
modelBuilder.Entity<ApplicationGroup>().ToTable("Groups")
.HasMany(x => x.Users)
.WithMany(x => x.Groups)
.Map(x =>
{
x.ToTable("GroupUsers");
x.MapLeftKey("GroupId");
x.MapRightKey("UserId");
});