我已經查看了類似錯誤的答案,但似乎無法找到對特定答案的答案錯誤。導航屬性Project.Models.Customer.SubCustomers的聲明類型與指定導航的結果不兼容
我運行了遷移,並且當種子法運行(遷移一直很好)錯誤發生。
導航屬性Project.Models.Customer.SubCustomers的聲明類型與指定導航的結果不兼容。
這是一個循環引用,即客戶可以有0 .. * SubCustomers和0..1 ParentCustomers。
客戶模式:
public class Customer : Entity
{
public int CustomerId { get; set;}
public string Name { get; set; }
// Relationships
public int? ParentCustomerId { get; set; }
public virtual ICollection<Customer> SubCustomers { get; set; } // a Customer has many Customers as SubCustomers, a Customer has zero or one ParentCustomer
// Other relationships
}
從上下文流利的API:
modelBuilder.Entity<Customer>()
.HasKey(customer => customer.CustomerId);
modelBuilder.Entity<Customer>()
.Property(customer => customer.Name)
.IsRequired()
.HasColumnType("nvarchar")
.HasMaxLength(500);
modelBuilder.Entity<Customer>() // a Customer has many Customers as SubCustomers, a Customer has zero or one ParentCustomer
.HasOptional(customer => customer.SubCustomers)
.WithMany()
.HasForeignKey(customer => customer.ParentCustomerId);
從播種方法:(客戶在數據庫中創建,分客戶不工作)
// Default Customers - create and save
var customers = new[]{
new Customer { Name = "Custa" },
new Customer { Name = "Custb" },
new Customer { Name = "Custc" }
};
context.Customers.AddOrUpdate(r => r.Name, customers[0], customers[1], customers[2]);
context.SaveChanges();
// Add SubCustomers b & c to Customer a (ids calculated beforehand, e.g. aId, as linq does not support array index)
var aId = customers[0].CustomerId;
var a = context.Customers.Include(c => c.SubCustomers).SingleOrDefault(c => c.CustomerId == aId);
if (a.SubCustomers == null)
a.SubCustomers = new List<Customer>();
var bId = customers[1].CustomerId;
var b = a.SubCustomers.SingleOrDefault(c => c.CustomerId == bId);
if (b == null)
a.SubCustomers.Add(context.Customers.Single(c => c.CustomerId == bId));
var cId = customers[2].CustomerId;
var c = a.SubCustomers.SingleOrDefault(c => c.CustomerId == cId);
if (c == null)
a.SubCustomers.Add(context.Customers.Single(c => c.CustomerId == cId));
context.SaveChanges();
如果有人能夠發現導致錯誤的原因,我將非常感激。非常感謝!
感謝您發表該問題和答案。今天早上我們一直在爲這個確切的問題奮鬥了幾個小時,這是我們指出了正確方向的帖子。謝謝。 – 2016-07-22 12:18:30