Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define Entity Framework relationships using foreign keys only by FluentAPI

Is any way of defining Entity Framework relations using foreign keys only (no virtual properties of reference type) with FluentAPI (data models should not be changed)?

CardDataModel

public class CardDataModel
{
    public int CardId { get; set; }

}

CheckItemDataModel

public class CheckItemDataModel
{
    public int CheckItemId { get; set; }
    public int CardId { get; set; }
}
like image 726
Alex Zaitsev Avatar asked Mar 08 '23 04:03

Alex Zaitsev


1 Answers

Yes, it's possible in EF Core. It wasn't in EF6 and below, but now EF Core provides parameterless overloads of HasMany / HasOne which allow configuring such relationship:

modelBuilder.Entity<CardDataModel>()
    .HasMany<CheckItemDataModel>() // <-- note this
    .WithOne()
    .HasForeignKey(e => e.CardId);
like image 177
Ivan Stoev Avatar answered Mar 25 '23 17:03

Ivan Stoev