问题
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