.net - EF Core 5:模型之间的依赖关系
问题描述
我有以下 2 个模型,位置和标称。Nominals 有一个 Location 的外键,Location 可以有许多不同的默认 Nominals 用于不同的目的。
public class Nominal
{
[Key]
public Guid Id { get; set; }
public string NominalCode { get; set; }
public string Description { get; set; }
public char Analysis { get; set; }
// link to location
public Guid LocationId { get; set; }
public Location Location { get; set; }
}
位置模型如下所示;
public class Location : AutoTracking
{
[Key]
public Guid Id { get; set; }
public int LocationCode { get; set; }
public string LocationName { get; set; }
[ForeignKey("Nominal")]
public Guid? DefaultNominal1Id { get; set; }
public Nominal DefaultNominal1 { get; set; }
[ForeignKey("Nominal")]
public Guid? DefaultNominal2Id { get; set; }
public Nominal DefaultNominal2 { get; set; }
}
由于 Nominal 已经具有 Location 链接,因此从 Location 返回 Nominal 的链接会生成错误。错误中建议的解决方案是将 [NotMapped] 属性添加到导航属性中,我已经这样做了。
添加未映射是否有任何副作用,我假设我仍然可以使用 EF 核心延迟加载加载导航属性?
解决方案
尝试更改您的课程:
public partial class Nominal
{
[Key]
public Guid Id { get; set; }
public string NominalCode { get; set; }
public string Description { get; set; }
public char Analysis { get; set; }
// link to location
public Guid LocationId { get; set; }
[ForeignKey(nameof(LocationId))]
[InverseProperty("Nominals")]
public virtual Location Location{ get; set; }
public partial class Location : AutoTracking
{
[Key]
public Guid Id { get; set; }
public int LocationCode { get; set; }
public string LocationName { get; set; }
[InverseProperty(nameof(Nominal.Location))]
public virtual ICollection<Nominal> Nominals{ get; set; }
}
如果由于某些原因您需要更多属性,您可以通过以下方式添加它们:
public partial class Location : AutoTracking
{
[NotMapped]
public Guid? DefaultNominal1Id { get; set; }
[NotMapped]
public Nominal DefaultNominal1 { get; set; }
[NotMapped]
public Guid? DefaultNominal2Id { get; set; }
[NotMapped]
public Nominal DefaultNominal2 { get; set;
}
但是您只能手动为它们分配值。
推荐阅读
- reactjs - NextJs:设置状态码 404 不重定向
- java - 如何模拟其对象在测试方法之外初始化的方法?
- python - 如果在以太坊地址中发现任何余额,我该如何设置停止?
- javascript - 为映射的对象元素赋予不同的样式
- python - 使用 Scapy 解析 pcap 文件中的 Modbus 数据包
- echarts - 根据数据更改 barWidth
- java - E/AndroidRuntime:致命异常:grpc-default-executor-0 PID:10113
- python - 遍历对象数组 - Python 哈希表
- javascript - 如何在 React js 中的 select 输入值中传递 html 标签?
- sql - How to use count "how many times a particular customer made inquiries"?