我正在使用ASP.NET MVC 4 Entity Framework 5为以下具有它们之间关系的类的数据库结构生成代码首次迁移。但是,每当我尝试从迁移中更新数据库时,我遇到了导致此错误的问题:
可以在此处找到迁移文件的粘贴文件夹: http://pastebin.com/ngXacrKV
错误返回:
Introducing FOREIGN KEY constraint 'FK_dbo.Bookings_dbo.Rooms_RoomId' on table 'Bookings' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
Bunk.cs
public class Bunk
{
[Key]
public int BunkId { get; set; }
public BunkStatus BunkStatus { get; set; }
[ForeignKey("Room")]
public int RoomId { get; set; }
public virtual Room Room { get; set; }
// Added for convenience
public virtual ICollection<Booking> Bookings { get; set; }
}
Room.cs
public class Room
{
[Key]
public int RoomId { get; set; }
public string RoomName { get; set; }
public Gender RoomGender { get; set; }
public RoomStatus RoomStatus { get; set; }
public virtual ICollection<Bunk> Bunks { get; set; }
// Added for convenience
public virtual ICollection<Booking> Bookings { get; set; }
}
Bookings.cs
public class Booking
{
[Key]
public int BookingId { get; set; }
//[ForeignKey("UserProfile")]
//public int UserProfileId { get; set; }
//public UserProfile UserProfile { get; set; }
[ForeignKey("Bunk")]
public int BunkId { get; set; }
public Bunk Bunk { get; set; }
public int Duration { get; set; }
[ForeignKey("Preferred_Room")]
public int RoomId { get; set; }
public Room Preferred_Room { get; set; }
public Decimal Price { get; set; }
public BookingStatus BookingStatus { get; set; }
}
在不对原始类结构造成太多干扰的情况下,最好的解决方法是删除此问题。我不太担心添加新的连接表,只要我仍然可以在我的控制器/视图模型中以延迟加载方式访问代码。
答案 0 :(得分:0)
您可以尝试指定Fluent API来设置无级联删除
public class YOURContext: DbContext{
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
// here is where fluent API goes.
// I suspected the error is EF wanting a NO cascade delete. Hence the suggestion to try
entity<Booking>.HasOptional(t => t.Bunk)
.WithOptionalPrincipal()
.WillCascadeOnDelete(false); // <<<<<< this is the option to try.
// you may also need to try the same with Preferred_Room as well.
答案 1 :(得分:0)
如果不需要级联删除,那么在数据库上下文类中,我们可以通过重写OnModelCreating方法为所有关系设置cascade delete为false,如下所示。默认EF使其级联删除,这就是为什么你得到循环或多个删除路径的例外。
public class MyContext: DbContext
{
//db sets defined
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<PrimaryKeyTable>().HasMany(x => x.ChildTableCollection).WithRequired(x =>
Key).WillCascadeOnDelete(false);
//In your case
modelBuilder.Entity<Bunk>().HasMany(x => x.Bookings).WithRequired(x =>
x.BunkId).WillCascadeOnDelete(false);
// same for room if required.
}
}