Entity Framework: Combining Objects into a Navigation Property

Considering these objects are automatically generated by EF ... (pseudo)

class CreditCard
{
    int ID {get;set;}
    string Number {get;set;}
}
class Person
{
    EntityCollection<CreditCard> CreditCards {get; set;}
}

      

What is the best way to combine an unlinked list into the CreditCards Person property.

The list will be built on a WebForm based on UserInput. The list will contain new credit cards (additions), changes to existing credit cards (updates), and will not contain CreditCards that the user has deleted.

Next (the task I need help with ) is to detach the list and merge it using the CreditCards property of the Person instance.

This merging process will (A) Add new instances to the list, (B) Update existing instances AND (C) Remove instances not in the disabled list.

Is there a defacto way that EF is designed to handle this, or is it a manual process? If there is a user manual, what is the best way to achieve this in a generic way that can be reused through objects?

+2


source to share


1 answer


Obviously, I'm pretty late to the party here, but if I'm not mistaken where your credit card list creditCardList

is of type List<CreditCard>

, what you want will be something like:

Person yourPerson = Context.Persons
                           .Include("CreditCards")
                           .First<Person>(p => p.PersonId == yourPersonId);

yourPerson.CreditCards.Clear();
creditCardList.ForEach(cc => yourPerson.CreditCards.Add(cc));
Context.SaveChanges();

      



I'm not sure if this doesn't work, or if there is anything extra you need.

+2


source







All Articles