c# - 零对多关系,还是别的什么?使用 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”进行区分
解决方案
从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)
在这种情况下也不需要,但就在这里。
推荐阅读
- python - 为什么我在使用 re.split 时在列表末尾得到一个空字符串?
- postgresql - PostgreSQL 存储哪些时区信息?
- r - 如何将 2 个散点图与 x = 平均年龄和 y = 冒险重叠?
- ios - 我的代码是否未正确实现 google chromecast 按钮和流式传输功能?
- hadoop - 连接到 hive 时 Presto “无法列出目录”
- android - 如何检测 NFC 标签移除事件?
- gremlin - Gremlin bothE() 是否双重计算边缘?
- android-studio - 使用ndk在android studio中启动应用程序时安装失败?
- java - 将大写日期解析为 LocalDate
- yii - Yii 1.1 urlManager .php?param=重定向