當我嘗試加載父實體的子實體時,它將加載默認值。如果我嘗試顯式加載它將拋出異常 多重性約束違反。關係'CodeFirstNamespace.Association_Customer'的角色'Association_Customer_Target'具有多重性1或0..1。檢索複雜圖形的子實體時引發此異常。加載父實體的子實體問題。單向映射和1到0..1與共享主鍵的關係?
我有一個圖表協會具有子實體客戶與一個0或1的關係,並具有獨立協會。* 主鍵 *被共享。我正在使用EF6。延遲加載已啓用。
public class Association
{
public virtual long Id { get; set; }
public virtual string ExternalId { get; set; }
public virtual int OrganizationId { get; set; }
public virtual AssociationType AssociationType { get; set; }
public virtual Customer Customer {get; set;}
public Association()
{
Customer = new Customer();
}
}
客戶類。
public class Customer
{
public virtual long Id { get; set; } //Shared primary key
public virtual ICollection<Item> Items {get; set;}
public virtual ICollection<Complaint> Complaints {get; set;}
public customer()
{
Items = new List<Item>();
Complaints = new List<Complaint>();
}
}
映射是單向的:
public class AssociationMapping:EntityTypeConfiguration<Association>
{
public AssociationMapping() : base()
{
HasKey(x => x.Id);
Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.ExternalId).IsRequired();
Property(x => x.OrganizationId).IsRequired();
Property(x => x.AssociationType);
HasOptional(x => x.Customer).WithRequired().WillCascadeOnDelete();
}
}
public class CustomerMapping : EntityTypeConfiguration<Customer>
{
public CustomerMapping():base()
{
HasKey(x => x.Id);
Property(x => x.Id);
HasMany(x => x.Items)
.WithOptional()
.HasForeignKey(key => key.CustomerId)
.WillCascadeOnDelete();
HasMany(x => x.Complaints)
.WithOptional()
.HasForeignKey(key => key.CustomerId)
.WillCascadeOnDelete();
}
}
當我載入我的關聯實體它完美地加載,但子實體客戶被載入默認值當我嘗試加載客戶明確其拋出異常。
var dbassociation = Single<Association>(x => x.OrganizationId== asso.organizationId && x.ExternalId == asso.ExternalId && x.AssociationType == asso.AssociationType);
dbassociation.Customer = Single<Customer>(x => x.id == dbassociation.id);
[更新:單方法]
public TEntity Single<TEntity>(System.Linq.Expressions.Expression<Func<TEntity, bool>>criteria) {
return Context.Set<TEntity>().SingleOrDefault(criteria); }
出於測試目的,我已經通過消除對關聯類顧客財產虛擬試圖急於負載,並試圖跟隨,但它拋出同樣的excepetion
Context.Configuration.LazyLoadingEnabled = false;
Context.Entry<Association>(dbassociation).Reference<Customer>(pa => pa.Customer).Load();
我也試過哪個拋出相同的異常
var dbassociation = Context.Set<Association>().Include("Customer").SingleOrDefault(x => x.OrganizationId== asso.organizationId && x.ExternalId == asso.ExternalId && x.AssociationType == asso.AssociationType);
現在我得出結論,儘管我使用不同的方法來檢索異常是一樣的。問題出在我猜的映射上。我感謝您的意見和建議。
「Association」和「Customer」之間的關係究竟是什麼?它是1:1,一對多等?哪個表格有FK參考? – IronMan84
我已經提到它是1:0..1主鍵在關聯和客戶之間共享。客戶有fk參考。 – Mady
從導航屬性中刪除'virtual'關鍵字並不意味着急切加載。 – haim770