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

c# entity-framework entity-framework-core

Question

I have a Product model with a foreign key property called ProductTypeId. However, I do not have a ProductType model. Instead, I have a TypeListItem model. I would like to tell EF to still create a relationship from ProductTypeId to the Id in TypeListItem table.

I would like to use Entity Framework Core fluent API to specify this, but can't figure out how. I believe I used to use HasRequired, but I don't think that is available in 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?

1
0
11/12/2016 4:35:20 PM

Popular Answer

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()).

The fluent configuration for your model the way it is now is:

modelBuilder.Entity<Product>()
    .HasOne<TypeListItem>()
    .WithMany()
    .HasForeignKey(e => e.ProductTypeId);
1
11/12/2016 5:04:08 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow