Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework core update many to many

We are porting our existing MVC6 EF6 application to Core.

Is there a simple method in EF Core to update a many-to-many relationship?

My old code from EF6 where we clear the list and overwrite it with the new data no longer works.

var model = await _db.Products.FindAsync(vm.Product.ProductId);
model.Colors.Clear();
model.Colors =  _db.Colors.Where(x => 
vm.ColorsSelected.Contains(x.ColorId)).ToList();
like image 545
Talnaci Sergiu Vlad Avatar asked Mar 24 '17 07:03

Talnaci Sergiu Vlad


People also ask

How do you create a many-to-many relationship in EF core?

Many-to-many relationships require a collection navigation property on both sides. They will be discovered by convention like other types of relationships. The way this relationship is implemented in the database is by a join table that contains foreign keys to both Post and Tag .

How do you insert a many-to-many relationship?

When you need to establish a many-to-many relationship between two or more tables, the simplest way is to use a Junction Table. A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table.


1 Answers

This will work for you.

Make a class to have the relationship in:

public class ColorProduct
{
    public int ProductId { get; set; }
    public int ColorId { get; set; }

    public Color Color { get; set; }
    public Product Product { get; set; }
}

Add a ColorProduct collection to your Product and Color classes:

 public ICollection<ColorProduct> ColorProducts { get; set; }

Then use this extension I made to remove the unselected and add the newly selected to the list:

public static void TryUpdateManyToMany<T, TKey>(this DbContext db, IEnumerable<T> currentItems, IEnumerable<T> newItems, Func<T, TKey> getKey) where T : class
{
    db.Set<T>().RemoveRange(currentItems.Except(newItems, getKey));
    db.Set<T>().AddRange(newItems.Except(currentItems, getKey));
}

public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other, Func<T, TKey> getKeyFunc)
{
    return items
        .GroupJoin(other, getKeyFunc, getKeyFunc, (item, tempItems) => new { item, tempItems })
        .SelectMany(t => t.tempItems.DefaultIfEmpty(), (t, temp) => new { t, temp })
        .Where(t => ReferenceEquals(null, t.temp) || t.temp.Equals(default(T)))
        .Select(t => t.t.item);
}

Using it looks like this:

var model = _db.Products
    .Include(x => x.ColorProducts)
    .FirstOrDefault(x => x.ProductId == vm.Product.ProductId);

_db.TryUpdateManyToMany(model.ColorProducts, vm.ColorsSelected
    .Select(x => new ColorProduct
    {
        ColorId = x,
        ProductId = vm.Product.ProductId
    }), x => x.ColorId);
like image 75
Paw Ormstrup Madsen Avatar answered Oct 23 '22 17:10

Paw Ormstrup Madsen