[英]Entity Framework 1:0..1 (One to zero or one) relationship using Data Annotations
尝试做一些我认为应该很简单的事情。
Customer
------
CustId
BillingId
ShippingId
...other customerInfo
Address
------
Id
...other addressinfo
我有相应的POCO
public class Customer {
[Key]
public int CustId {get;set;}
[Column("BillingId")]
[ForeignKey("BillingAddress")
public int? BillingId {get;set;}
public virtual Address BillingAddress{get;set;}
[Column("ShippingId")]
[ForeignKey("ShippingAddress")
public int? ShippingId {get;set;}
public virtual Address ShippingAddress{get;set;}
...others...
}
public class Address {
[Key]
public int AddressId{get;set}
... others...
}
BillingId
和ShippingId
nullable
为nullable
因为客户可能已经或可能尚未设置地址。 我假设使用EF,如果这些值为null,则ShippingAddress
和BillingAddress
值也应该为null
。 当我查看运行应用程序时要返回的对象时,我的Customer
对象上的所有数据都已设置,但在ShippingAddress
/ BillingAddress
字段上,在调试模式下检查对象时,出现以下错误:
BillingAddress = '((System.Data.Entity.DynamicProxies.CustomerD_E865AA67CAAA399D4F193A2439775301DFD2F05115619BC048699B20BF6F7B11)details).BillingAddress'
threw an exception of type 'System.InvalidOperationException'
对于ShippingAddress
字段,将出现相同的错误。 该应用程序实际上继续运行,只有在调试中进行更多检查时才会抛出异常。 对于特定的检查对象,将正确填充ShippingId
和BillingId
。
不知道为什么在我的设置下会发生这种情况。
一个可能的原因是:您的存储库在DI configure中注册为单例。
另一个可能的原因:在导航属性中添加ForeignKey
和InverseProperty
public class Customer {
[Key]
public int CustId {get;set;}
//[Column("BillingId")]//not necessary if real column is same as property
public int? BillingId {get;set;}
[ForeignKey("BillingId")]
[InverseProperty("Customer")]
public Address BillingAddress{get;set;} //no need to be virtual
//[Column("ShippingId")]
public int? ShippingId {get;set;}
[ForeignKey("ShippingId")]
[InverseProperty("Customer")]//InverseProperty: Specifies the inverse of a navigation property that represents the other end of the same relationship.
public Address ShippingAddress{get;set;} //no need to be virtual
...others...
}
在新项目中尝试Scaffold-DbContext
来验证您的pocos:
https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/cli/powershell#scaffold-dbcontext
Scaffold-DbContext "your connection string" -DataAnnotations -OutputDir "Models" -Force
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.