首页 > 解决方案 > 零对多关系,还是别的什么?使用 FluentAPI

问题描述

我有一个这样定义的“项目”表:

item_id
Name
Description
itemseries_id
itemtype_id
itemcondition_id

然后我有“ItemForSale”表:

itemforsale_id
item_id
price
date_added

实体:

public class Item
{
    public int ItemId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public int ItemSeriesId { get; set; }
    public ItemSeries ItemSeries { get; set; }

    public int ItemConditionId { get; set; }
    public ItemCondition ItemCondition { get; set; }

    public int ItemTypeId { get; set; }
    public ItemType ItemType { get; set; }

    public List<ItemTag> ItemTags { get; set; }
    public List<ItemImage> ItemImages { get; set; }
    public List<ItemPurchase> ItemPurchases { get; set; }
    public List<ItemSale> ItemSales { get; set; }
}
public class ItemForSale
{
    public int ItemForSaleId { get; set; }
    public decimal Price { get; set; }
    public DateTime AddedDate { get; set; }

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

我将如何在这些之间使用 FluentAPI?我知道我可以在 Item 实体类中添加对 ItemForSale 的引用,但这对我来说没有意义。到目前为止,我已经映射了我所有的一对一和多对多关系,但是 Item 和 ItemForSale 之间的关系让我感到困惑。

注意:我将已作为“Sale”或“ItemSale”出售的物品和没有买家的待售物品作为“ItemForSale”进行区分

标签: c#entity-framework-coreef-fluent-api

解决方案


EF Core Docs,您可以执行以下操作:

class MyContext : DbContext
{
    public DbSet<Item> Items { get; set; }
    public DbSet<ItemSale> ItemSales { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ItemSale>()
            .HasOne(p => p.Item)
            .WithMany(b => b.ItemSales)
            .HasForeignKey(p => p.ItemId)
            .IsRequired(false);
    }
}

public class Item
{
    public int ItemId { get; set; }
    public string Url { get; set; }

    public List<ItemSale> ItemSales { get; set; }
}

public class ItemSale
{
    public int ItemSaleId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public Item Item { get; set; }
    
    // note that the reference id is nullable
    public int? ItemId { get; set; }
}

然后,将ItemId模型类中的属性标记为int?. 在 EF 6 上,我们有HasOptional配置选项,但在 EF Core 上,如果引用属性可以为空,则假定该属性从 0 开始,例如0..N. 我认为即使IsRequired(false)在这种情况下也不需要,但就在这里。


推荐阅读