简体   繁体   中英

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.

I then have a entity called BankingRun which contains a list of 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.

The problem occurs when I want to delete the BankingRun without affecting the CollectedBags table at all. A CollectedBags record doesn't always belong to a 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

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

With Fluent API use this code:

 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);

It will prevent that when you delete one entity all others related get deleted as well, basically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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