简体   繁体   中英

Comparing and insert/update/delete children in Entity Framework

I have a multiple selection form that needs to be saved into the database. Users can edit their selections on their subsequent visits. The items are defined in a table with unique IDs so the form only pass back a list of IDs.

It is something like:

Fruits:
    { id=1, name="apple" }
    { id=2, name="orange" }
    { id=3, name="banana" }

People:
    { id=1, name="user", fruits=apple,orange }

In DB there is a link table linking the id of people and id of fruits.

Now when I receive a request to edit, I'll need to compare with existing fruits so I know whether I need to add or delete an entry.

foreach (var fruit in existing_fruits)
{
    if (post_fruits.Where(e => e.id == fruit.id).Count() == 0) user.Fruits.Remove(fruit);
}

foreach (var fruit in post_fruits)
{
    if (existing_fruits.Where(e => e.id == fruit.id).Count() == 0)
    {
        var entity = context.Fruit.Where(e => e.id == fruit.id);
        user.Fruits.Add(entity);
    }
}

As you can see there are multiple loops and multiple which call on the lists, which makes me wonder if there is a cleaner way in doing this?

What if you use .Any method here (although it still uses two loops but it is more efficient) :

foreach (var fruit in existing_fruits)
    if (!post_fruits.Any(e => e.id == fruit.id)) user.Fruits.Remove(fruit);

foreach (var fruit in post_fruits)
{
    if (existing_fruits.Any(e => e.id == fruit.id)) continue;
    var entity = context.FirstOrDefault(e => e.id == fruit.id);
    if(entity != null) user.Fruits.Add(entity);
}

But it's better to change DB architecture to:

Fruits:
    { id=1, name="apple" }
    { id=2, name="orange" }
    { id=3, name="banana" }

People:
    { id=1, name="user" }

PeopleFruits
    { id=1, fruitId = 1, personId = 1, isSelected = 0}

All you need to update records now is to get this PeopleFruits entities of some person.

PeopleFruits[] personPplFruits = cont.PeopleFruits.Where(pf => pf.personId == 1).ToArray();

And update .isSelected properties according to what user has selected.

Check this article please : https://www.simple-talk.com/sql/database-administration/how-to-get-database-design-horribly-wrong/

There are a lot of useful functions in EntityFramework.Extended . It contains Batch Update and Delete feature which can be useful in your situation, it also eliminates the need to retrieve and load an entity before modifying it, so it can increase your performance in future.

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