1

我有以下两个实体如何设置NOT NULL外键的属性多重关系

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外键列。

但是,由于与用户的另一种关系,似乎不可能。 有没有解决方法?

回答

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); 
} 
+0

UserByCreated和UserByCreatedId性能在预定实体不用户实体,所以“modelBuilder.Entity ().HasRequired(B => b.UserByCreated).WithMany()。HasForeignKey(B => b.UserByCreatedId) ;“可能是正确的。顺便说一句,即使我做了你的建议,我得到了以下异常:“在表'BookingUsers'上引入FOREIGN KEY约束'FK_BookingUsers_Users_UserId'可能导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。\ r \ n不能创建约束。请参阅以前的错误。“ – Ray 2012-02-20 10:22:11

+0

欲了解更多信息,我还添加流畅的api为多对多关系如下“modelBuilder.Entity () .HasMany(b => b.Members) .WithMany(u => u.Bookings) 。地图(M => { m.ToTable( “BookingUsers”); m.MapLeftKey( “BookingId”); m.MapRightKey( “用户ID”); }); – Ray 2012-02-20 10:24:53

+0

@Ray编辑我的回答你会的。必须添加'WillCascadeOnDelete(false)'到一个可能的关系 – Eranga 2012-02-20 10:39:52