EF CodeFirst向自联接关系添加列
本文关键字:关系 添加 CodeFirst EF | 更新日期: 2023-09-27 18:01:04
所以我使用的是asp标识ApplicationUser有FriendRequest,这就是我所做的
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
FriendRequests = new Collection<ApplicationUser>();
}
public virtual ICollection<ApplicationUser> FriendRequests {get; set;}
}
这是我的Fluent Api Mapping
modelBuilder.Entity<ApplicationUser>()
.HasMany(x => x.FriendRequests)
.WithMany()
.Map(x =>
{
x.MapLeftKey("UserRequestingID");
x.MapRightKey("UserBeingRequestedID");
x.ToTable("FriendRequests");
});
这将创建一个包含两列"UserRequestingID"answers"UserBeingRequestedID"的表"FriendRequests"。
我想在这个表中添加一个额外的列"isIgnored",我该怎么做?我能这样做吗?还是我应该创建一个新类?
提前感谢。
只有在连接表中不包含PK以外的其他列时,才支持通过映射的many-to-many
关系。因此,是的,如果您想包含其他列,则需要创建显式实体并设置2个one-to-many
关系。
类似这样的东西:
型号:
public class ApplicationUser : IdentityUser
{
// ...
public virtual ICollection<FriendRequest> FriendRequests {get; set;}
public virtual ICollection<FriendRequest> FriendRequested {get; set;}
}
public class FriendRequest
{
public string UserRequestingID { get; set; }
public string UserBeingRequestedID { get; set; }
public bool IsIgnored { get; set; }
public virtual ApplicationUser UserRequesting { get; set; }
public virtual ApplicationUser UserBeingRequested { get; set; }
}
配置:
modelBuilder.Entity<FriendRequest>()
.HasKey(e => new { e.UserRequestingID, e.UserBeingRequestedID });
modelBuilder.Entity<FriendRequest>()
.HasRequired(e => e.UserRequesting)
.WithMany(e => e.FriendRequests)
.HasForeignKey(e => e.UserRequestingID)
.WillCascadeOnDelete();
modelBuilder.Entity<FriendRequest>()
.HasRequired(e => e.UserBeingRequested)
.WithMany(e => e.FriendRequested)
.HasForeignKey(e => e.UserBeingRequestedID)
.WillCascadeOnDelete();