尝试做一些我认为应该很简单的事情。
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
,因为客户可能尚未设置地址。我假设使用EF,如果这些值为空,则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
。
不确定我的设置为何会发生这种情况。
答案 0 :(得分:0)
一个可能的原因是:您的存储库已在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/en-us/ef/core/miscellaneous/cli/powershell#scaffold-dbcontext
Scaffold-DbContext "your connection string" -DataAnnotations -OutputDir "Models" -Force