0

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

1
  • Can you post more code, please? Also, the error message would be useful. Commented Oct 29, 2013 at 15:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help. Unless I am missing something, when I did this it caused an error when creating my BankingRun saying that it couldn't cast a list of CollectedBags to type CollectedBags. I don't fully understand how your solution works but I don't want CollectedBags to be an optional dependent within the BankingRun. I NEED the relationship when the BankingRun exists, however I need it to go away completely when wanting to remove one.
As I said, this is an illustration. You'll need to adjust the code accordingly, but the thing here is the cascade on delete;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.