简体   繁体   English

实体框架代码优先参考约束问题

[英]Entity Framework Code First Reference constraint issue

I am having problems with my model and trying to delete records. 我的模型出现问题,并试图删除记录。 I have reduced it to try and show the issue I am having 我已将其缩小以尝试显示我遇到的问题

I have a entity called CollectedBags with an Id and name. 我有一个名为CollectedBags的实体,具有一个ID和名称。

I then have a entity called BankingRun which contains a list of CollectedBags 然后,我有一个名为BankingRun的实体,其中包含CollectedBags的列表

public virtual List<CollectedBags> Bags { get; set; }

This model automatically adds a relationship between the two, and in the database it adds a column to collectedbags to reference the BankingRun. 该模型自动在两者之间添加关系,并且在数据库中向收集的包中添加一列以引用BankingRun。

The problem occurs when I want to delete the BankingRun without affecting the CollectedBags table at all. 当我想删除BankingRun而完全不影响CollectedBags表时,会出现问题。 A CollectedBags record doesn't always belong to a BankingRun. CollectedBags记录并不总是属于BankingRun。 Anything I try to delete a record results in a conflict between the two tables obviously, but my lack of knowledge with entity framework is leaving me stuck without writing some SQL to physically remove the Banking Run id in CollectedBags 我尝试删除记录的任何事情显然都会导致两个表之间的冲突,但是我对实体框架的缺乏了解使我陷入困境,而没有编写一些SQL来物理删除CollectedBags中的Banking Run ID

public class CollectedBags
{
    public long CollectedBagsId { get; set; }
    public string Name { get; set; }
}

public class BankingRun
{
    public long BankingRunId { get; set; }

    public DateTime DateTimeVisited { get; set; }

    public virtual List<CollectedBags> Bags { get; set; }
}

I am then trying to delete a BankingRun after its been created with multiple CollectedBags 然后,我尝试使用多个CollectedBags创建BankingRun后删除它

With Fluent API use this code: 对于Fluent API,请使用以下代码:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(false);
    }

This is just an illustration, but the important thing here is the .WillCascadeOnDelete(false); 这只是一个例子,但重要的是.WillCascadeOnDelete(false);

It will prevent that when you delete one entity all others related get deleted as well, basically. 基本上,这将防止在删除一个实体时所有其他相关实体也被删除。

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

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