如何處理ef core的多對多關係?

如何處理ef core的多對多關係?

多對多關係不像其他關係那麼簡單,在這篇文章中,我將向您展示如何創建多對多關係以及如何在 ef core 中使用它們。

最后更新 2021/11/2 下午8:47
Zbigniew
预计阅读 5 分钟
分类
EF Core
标签
.NET EF Core ORM

多對多關係不像其他關係那麼簡單,在這篇文章中,我將向您展示如何創建多對多關係以及如何在 ef core 中使用它們。

模型

多对多的简单而实用的例子可能是某种数字电子商务商店。用户可以将商品放入购物车(一个购物车可以有多个商品),而商品属于多个购物车。让我们从创建CartItem类开始。

public class Cart
{
    public int Id { get; set; }

    public ICollection<Item> Items { get; set; }
}
public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Quantity { get; set; }

    public ICollection<Cart> Carts { get; set; }
}

這看起來不錯,但它不起作用。在本文發表時,ef core 無法處理這種情況。看起來 ef core 不知道如何處理這種關係,當您嘗試添加遷移時,您會得到以下結果:

Unable to determine the relationship represented by navigation property ‘Cart.Items’ of type ‘ICollection’. Either manually configure the relationship, or ignore this property using the ‘[NotMapped]’ attribute or by using ‘EntityTypeBuilder.Ignore’ in ‘OnModelCreating’.

【無法確定類型為“icollection< item>”的導航屬性“cart.items”表示的關係。手動配置關係,或使用“[notmapped]”屬性或使用“onmodelcreating”中的“entitytypebuilder.ignore”忽略此屬性。】

我们需要做的第一件事是手动创建另一个“中间”类(表),它将建立CartItem的多对多关系,让我们创建这个类:

public class CartItem
{
    public int CartId { get; set; }
    public Cart Cart { get; set; }

    public int ItemId { get; set; }
    public Item Item { get; set; }
}

我们创建了关联CartItem的新类CartItem,我们还需要更改它们各自的导航属性:

public class Cart
{
    public int Id { get; set; }

    public ICollection<CartItem> Items { get; set; }
}
public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Quantity { get; set; }

    public ICollection<CartItem> Carts { get; set; }
}

如果您現在嘗試添加遷移,則會出現另一個錯誤:

The entity type ‘CartItem’ requires a primary key to be defined.

【實體類型“cartitem”需要定義一個主鍵。】

对,CartItem没有主键, 由于它是多对多关系,因此它应该具有复合主键。复合主键类似于常规主键,但它由两个属性(列)而不是一个属性组成。目前,创建复合键的唯一方法是在OnModelCreating.

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<CartItem>().HasKey(i => new { i.CartId, i.ItemId });
}

最後,我們的資料庫結構可以由 entityframework 處理,我們可以繼續遷移了。

插入多對多

假设我们已经有CartItem在我们的数据库中,现在我们想将特定商品(Item)添加到特定购物车(Cart),为了做到这一点,我们需要创建新的 CartItem 并保存它。

var cart = db.Carts.First(i => i.Id == 256);
var item = db.Items.First(i => i.Id == 1024);

// 可以使用两个类的主键ID进行关联
var cartItem = new CartItem
{
    CartId = cart.Id,
    ItemId = item.Id
};

// 也可以使用两个类实体进行关联
var cartItem = new CartItem
{
    Cart = cart,
    Item = item
};

db.Add(cartItem);
db.SaveChanges();

在多對多中檢索相關數據

从数据库中获取数据相当简单,注意使用Include关联检索相关数据。这里总共涉及 3 个表:Cart, Item, CartItem(将商品Item与购物车Cart关联起来)。

// 获取关联所有商品的指定购物车
var cartIncludingItems = db.Carts.Include(cart => cart.Items).ThenInclude(row => row.Item).First(cart => cart.Id == 1);
// 获取指定购物车的所有商品
var cartItems = cartIncludingItems.Items.Select(row => row.Item);

另外,有些操作可以不使用關係來執行。例如,如果您有購物車 id,則可以使用以下 linq 一次獲取所有商品:

var cartId = 1;
var cartItems = db.Items.Where(item => item.Carts.Any(j => j.CartId == cartId));

相同的原則適用於相反的用例,這意味著您可以應用上述模式來獲取具有特定項目的所有購物車。

從多對多中刪除

删除是指删除购物车Cart和商品Item之间的关系CartItem。在以下示例中,我们不会删除购物车Cart或商品Item,只会删除购物车Cart和商品Item之间的关系CartItem

让我们从购物车Cart中删除单个产品Item开始。

var cartId = 1;
var itemId = 1;
var cartItem = db.CartsItems.First(row => row.CartId == cartId && row.ItemId == itemId);

db.Remove(cartItem);
db.SaveChanges();

然後,讓我向您展示如何從購物車中刪除所有項目。

var cart = db.Carts.Include(c=> c.Items).First(i => i.Id == 2);

db.RemoveRange(cart.Items);
db.SaveChanges();

原文作者:zbigniew

原文標題:how to handle many-to-many in entity framework core

原文連結:https://softdevpractice.com/blog/many-to-many-ef-core/

翻譯:沙漠盡頭的狼

Keep Exploring

延伸阅读

更多文章