2015-07-19 111 views
0

我有三个型号,用户,房间和PlayerRoom这样定义:实体框架多级联删除

public class User 
{ 
    public int id { get; set; } 
    public string UserName { get; set; } 

    //flags user to be deleted when room is no longer available 
    public bool temporaryUser { get; set; } 

    [JsonIgnore] 
    public bool permanent { get; set; } 
} 

public class Room 
{ 
    public int id { get; set; } 
    public string RoomName { get; set; } 

    [JsonIgnore] 
    public int CreatedById { get; set; } 
    public virtual User CreatedBy { get; set; } 
} 


public class PlayerRoom 
{ 
    public int id { get; set; } 

    [JsonIgnore] 
    public int RoomId { get; set; } 
    public virtual Room Room { get; set; } 

    [JsonIgnore] 
    public int UserId { get; set; } 
    public virtual User User { get; set; } 
} 

我想要做到的是建立模型,以便当User被删除或当Room被删除时,所有关联的PlayerRoom被删除。

目前,当我生成的迁移和运行update-database我得到的错误:

Introducing FOREIGN KEY constraint 'FK_dbo.Rooms_dbo.Users_CreatedById' on table 'Rooms' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 

无法创建约束。查看以前的错误。

从我做了什么研究是因为PlayerRoom可以从级联删除多种方式,但是,这是预期的行为。

如何获得迁移工具以生成不会导致此错误的迁移?

谢谢!

+0

你生成从数据库或代码第一种方法的实体? – Agalo

+0

我首先使用代码 – nealruggles1

回答

0

我最终改变了我的类,使它们更具限制性,在这种情况下实际上效果更好。我删除了PlayerRoom对象并将Room引用移到了用户对象上。

public class User 
{ 
    public int id { get; set; } 
    public string UserName { get; set; } 

    //flags user to be deleted when room is no longer available 
    public bool temporaryUser { get; set; } 

    public bool? isHost { get; set; } 

    [JsonIgnore] 
    public int? RoomId { get; set; } 
    public virtual Room Room { get; set; } 

    [JsonIgnore] 
    public bool permanent { get; set; } 
} 

public class Room 
{ 
    public int id { get; set; } 
    public string RoomName { get; set; } 
} 

通过移动Room给用户,而不是一个单独的对象会限制上的用户只能在一个Room和摆脱我的级联删除问题使用

0

gets rid of my cascading delete issue

EF代码首先设置级联默认为开启。从模型中把它关掉一个既可以在战略位置“WillCascadeOnDelete`关闭有问题的实体:

.WillCascadeOnDelete(false); 

或全球

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); 
+0

感谢您抽出时间写出答案,但我希望级联删除发生而不是禁用它。 – nealruggles1