我有两个实体
public class User
{
[Key]
public int Id { get; set; } // PK
// for many-to-many relation with Booking.Members
public virtual ICollection<Booking> Bookings { get; set; }
}
public class Booking
{
public Booking()
{
Members = new List<User>();
}
public int Id { get; set; } // PK
[ForeignKey("UserByCreated")]
public int UserByCreatedId { get; set; } // FK
public virtual User UserByCreated { get; set; }
// for many-to-many relation with User.Bookings
public virtual ICollection<User> Members { get; set; }
}
如上所示,用户和预订有两种不同的关系,一种是多对多关系,另一种是外键关系。
我想要做的是在Bookings表中使用带有NOT NULL条件的UserByCreatedId外键列。
然而,由于与User的另一种关系,似乎不可能。 对此有什么解决方案吗?
答案 0 :(得分:2)
使用Fluent API配置关系,因为当两个实体之间存在多个关系时,EF无法识别关系。
修改强>
UserByCreated
关系需要更改为可选,以避免多个删除路径问题。
public class Booking
{
public Booking()
{
Members = new List<User>();
}
public int Id { get; set; } // PK
[ForeignKey("UserByCreated")]
public int? UserByCreatedId { get; set; } // FK
public virtual User UserByCreated { get; set; }
public virtual ICollection<User> Members { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(u => u.Bookings)
.WithMany(b => b.Members);
modelBuilder.Entity<Booking>().HasOptional(u => u.UserByCreated)
.WithMany()
.HasForeignKey(b => b.UserByCreatedId)
.WillCascadeOnDelete(false);
}