[英]Mapping a foreign key w/ a different name using Entity Framework Core Fluent API
我有一個帶有外鍵屬性ProductTypeId
的Product模型。 但是,我沒有ProductType
模型。 相反,我有一個TypeListItem
模型。 我想告訴EF仍要創建從ProductTypeId
到TypeListItem
表中的Id
的關系。
我想使用Entity Framework Core fluent API來指定此名稱,但不知道如何使用。 我相信我曾經使用過HasRequired
,但我認為EF Core中不可用。
這是有問題的模型:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int ProductTypeId { get; set; }
}
public class TypeListItem
{
public int Id { get; set; }
public string Name { get; set; }
}
我相信我可能需要將TypeListItem
的導航屬性添加到Product
模型中,以使這成為可能,對嗎?
在EF Core中,甚至沒有導航屬性也是可能的,因為HasXYZ
/ WithXYZ
方法都具有無參數重載(btw,而不是XYZRequired
/ XYZOptional
,EF Core使用XYZOne
,可以與IsRequired()
結合使用)。
您的模型的流暢配置現在是:
modelBuilder.Entity<Product>()
.HasOne<TypeListItem>()
.WithMany()
.HasForeignKey(e => e.ProductTypeId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.