简体   繁体   English

使用Entity Framework Core Fluent API映射具有不同名称的外键

[英]Mapping a foreign key w/ a different name using Entity Framework Core Fluent API

I have a Product model with a foreign key property called ProductTypeId . 我有一个带有外键属性ProductTypeId的Product模型。 However, I do not have a ProductType model. 但是,我没有ProductType模型。 Instead, I have a TypeListItem model. 相反,我有一个TypeListItem模型。 I would like to tell EF to still create a relationship from ProductTypeId to the Id in TypeListItem table. 我想告诉EF仍要创建从ProductTypeIdTypeListItem表中的Id的关系。

I would like to use Entity Framework Core fluent API to specify this, but can't figure out how. 我想使用Entity Framework Core fluent API来指定此名称,但不知道如何使用。 I believe I used to use HasRequired , but I don't think that is available in EF Core. 我相信我曾经使用过HasRequired ,但我认为EF Core中不可用。

Here are the models in question: 这是有问题的模型:

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

I believe I might need to add a navigation property of TypeListItem to the Product model to make this possible right? 我相信我可能需要将TypeListItem的导航属性添加到Product模型中,以使这成为可能,对吗?

In EF Core it's possible even without navigation properties, because both HasXYZ / WithXYZ methods have parameterless overloads (btw, rather than XYZRequired / XYZOptional , EF Core uses XYZOne which can be combined with IsRequired() ). 在EF Core中,甚至没有导航属性也是可能的,因为HasXYZ / WithXYZ方法都具有无参数重载(btw,而不是XYZRequired / XYZOptional ,EF Core使用XYZOne ,可以与IsRequired()结合使用)。

The fluent configuration for your model the way it is now is: 您的模型的流畅配置现在是:

modelBuilder.Entity<Product>()
    .HasOne<TypeListItem>()
    .WithMany()
    .HasForeignKey(e => e.ProductTypeId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM