我已经查看了类似错误的答案,但我似乎无法找到我的特定错误的答案。
我正在运行迁移,并且在运行种子方法时发生错误(迁移工作正常)。
导航属性 Project.Models.Customer.SubCustomers 的声明类型与指定导航的结果不兼容。
这是一个循环引用,即客户可以有 0..* 子客户和 0..1 父客户。
客户型号:
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();
如果有人能发现导致错误的原因,我将不胜感激。非常感谢!