Define Entity Framework relationships using foreign keys only by FluentAPI

拜拜、爱过 提交于 2020-03-19 07:58:13

问题


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

回答1:


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



回答2:


You could do this.

public class Card
{
    public int Id { get; set; }
}

public class CheckItem
{
    public int Id { get; set; }
    public int CardId { get; set; }
    public virtual Card Card { get; set; }
}


来源:https://stackoverflow.com/questions/45999242/define-entity-framework-relationships-using-foreign-keys-only-by-fluentapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!