我有两个表T_users和M_Album,如下所示:
T_Users
T_Album
2个外键字段用户ID,M_Album中的ParentID以及T_Users中都有主键字段ID。如何在代码中首先编写实体代码?
我创建了
M_Album = new HashSet<M_Album>();
和
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<M_Album> M_Album { get; set; }
在T_Users.And
M_Album中的 public virtual T_Users T_Users { get; set; }
同时创建:
modelBuilder.Entity<T_Users>()
.HasMany(e => e.M_Album)
.WithOptional(e => e.T_Users)
.HasForeignKey(e => e.UserID);
modelBuilder.Entity<T_Users>()
.HasMany(e => e.M_Album)
.WithOptional(e => e.T_Users)
.HasForeignKey(e => e.ParentID);
这项工作正常还是其他方法?
答案 0 :(得分:0)
如果你有两个FK到另一个表,你还应该在主表声明中指定两个IColletion
。尝试使用数据注释方法而不是fluen api:
public class T_User
{
[InverseProperty("User")]
public virtual ICollection<T_Album> userAlbums {get; set;}
[InverseProperty("Parent")]
public virtual ICollection<T_Album> parentAlbums {get; set;}
//other stuff...
}
public class T_Album
{
[ForeignKey("User")]
public int UserId {get;set;}
public virtual T_User User {get; set;}
[ForeignKey("Parent")]
public int ParentId {get;set;}
public virtual T_User Parent {get; set;}
//other stuff...
}