0

I have a many-to-many relation between customers (for example a company) and persons. Adding new already stored persons to a company is working, but how do I delete an association between those 2, in case some person stops working in this company?

I don't want to delete the person or the company. Just the entry in my customer_person joining table.

Something like:

context.Entry(someCustomer.somePerson).State = System.Data.Entity.EntityState.Deleted;

deletes the person. That's not what I want.

  • chechk this link: the same question [ManyToMany](https://stackoverflow.com/questions/20052438/removing-many-to-many-entity-framework) – Marwen Jaffel Dec 10 '19 at 14:58
  • wouldn't ```artist.ArtistTypes.Remove(artistType);``` delete the ArtistType? In my case the person – Matthias F Dec 10 '19 at 15:00
  • remove the artistType from list of artistType in artist , not remove the artistType from database – Marwen Jaffel Dec 10 '19 at 15:02
  • I have tried it and it works exactly as needed. Thank you :) – Matthias F Dec 10 '19 at 15:58
  • check my answer useful – Marwen Jaffel Dec 10 '19 at 16:14
  • Sorry I just created this account. How do I do this? I only see the flag to mark your answer as a problem. I think I don't have the privilege to upvote until I have 15 reputation. – Matthias F Dec 11 '19 at 07:20
  • A comment is not an answer. @MarwenJaffel the way to go here is vote to close this question as duplicate. Matthias, you can do that too. This way Stack Overflow tries to avoid duplicated content while creating signposts to useful content. – Gert Arnold Dec 25 '19 at 21:57

1 Answers1

0

the proper way of doing this is:

1st in your dbcontext add the cascade delete conventions.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Conventions.Add<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Add<ManyToManyCascadeDeleteConvention>();

        base.OnModelCreating(modelBuilder);
}

and then in your POCO classes the relations you don't want to delete declare the properties either as string or int?depending on the master primary key type

example:

public int? personRefno {get;set;}
or
public string personRefno {get;set;}   

when the type is nullable such as string or int? (note when you add question mark it means nullable)

EF does not delete the related record, keeps that and set the personRefno to null

Asım Gündüz
  • 1,257
  • 3
  • 17
  • 42