我在我的Entity Framework项目中将Customer
的导航属性添加到Purchase
(作为集合)。该关系之前已经存在,因此不会执行数据库迁移。
当我检索一组非空的Product
- 它也有Purchase
的导航属性(作为集合)时 - 从上下文中,我得到以下异常:
'BrandedProduct'上的'BrandID'属性无法设置为'null'值。您必须将此属性设置为类型为“System.Int32”的非空值。
简化代码(所有实体也有ID属性和protected / public空构造函数):
public class Customer {
// Adding this line causes the exception. Without it, everything works fine.
public virtual ICollection<Purchase> Purchases { get; private set; }
}
public abstract class Product {
public virtual ICollection<Purchase> Purchases { get; private set; }
}
public class BrandedProduct : Product {
// This is the property that EF tries to set to null
public int BrandID { get; private set; }
public virtual Brand Brand { get; private set; }
}
public class Brand {}
// This works as a many-to-many relationship between Product and Customer
public class Purchase {
public int CustomerID { get; private set; }
public int ProductID { get; private set; }
public virtual Customer Customer { get; private set; }
public virtual Product Product { get; private set; }
// Other properties...
}
Purchase
类具有复合主键,因此在DataContext类中设置了以下配置。
public class DataContext : DbContext {
protected override void OnModelCreating(DbModelBuilder builder) {
builder.Entity<Purchase>().HasKey(x => new { x.CustomerID, x.ProductID });
}
}
知道为什么会这样吗?
答案 0 :(得分:0)
在此示例中,问题似乎是由于BrandedProduct
没有实体框架所需的主键。它试图找出并设置BrandID
作为主键,它有一个私人设置器。
要解决此问题,只需将[Key]
属性或其他HasKey
添加到配置中,即可获得包含公共设置器的属性。