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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.