零对多关系,还是其他?使用 Fluent API

Zero-to-many relationship, or something else? Using FluentAPI

我有一个“项目”table 定义如下:

item_id
Name
Description
itemseries_id
itemtype_id
itemcondition_id

然后我有“ItemForSale”table:

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 实体 class 中添加对 ItemForSale 的引用,但这对我来说没有意义。到目前为止,我已经映射了我所有的一对一和多对多关系,但是 Item 和 ItemForSale 之间的关系让我很困惑。

注意:我将已售出的商品区分为“特卖”或“ItemSale”和没有买家的待售商品“ItemForSale”

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; }
}

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