繁体   English   中英

实体框架多级删除

[英]Entity Framework Multiple Cascading Delete

我定义了以下三个模型:User,Room和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 ,但这是预期的行为。

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

谢谢!

我最终改变了我的课程,以使他们更具限制性,在这种情况下,实际上效果更好。 我删除了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并且摆脱了我的级联删除问题

摆脱了我的级联删除问题

EF使用“代码优先”功能默认将级联设置为启用。 要从模型中将其关闭,可以策略性地将“ WillCascadeOnDelete”从相关实体上移开:

.WillCascadeOnDelete(false);

或全球

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM