使用数据注释的实体框架1:0..1(一对​​零或一个)关系

时间:2018-07-23 20:40:55

标签: c# .net entity-framework-6

尝试做一些我认为应该很简单的事情。

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

BillingIdShippingIdnullable,因为客户可能尚未设置地址。我假设使用EF,如果这些值为空,则ShippingAddressBillingAddress的值也应该为null。当我查看运行应用程序时返回的对象时,在调试中,Customer对象上的所有数据都已设置,但ShippingAddress / BillingAddress字段中的所有数据都已设置模式在检查对象时出现以下错误:

BillingAddress = '((System.Data.Entity.DynamicProxies.CustomerD_E865AA67CAAA399D4F193A2439775301DFD2F05115619BC048699B20BF6F7B11)details).BillingAddress' 
threw an exception of type 'System.InvalidOperationException'

ShippingAddress字段出现相同的错误。该应用程序实际上继续运行,只有在调试中进行更多检查时才会抛出异常。对于特定的检查对象,正确填充了ShippingIdBillingId

不确定我的设置为何会发生这种情况。

1 个答案:

答案 0 :(得分:0)

一个可能的原因是:您的存储库已在DI configure中注册为单例。

另一个可能的原因:将ForeignKeyInverseProperty添加到导航属性

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