[英]Entity Framework tries setting property to null when querying, after new navigation property is added
I add a navigation property from Customer
to Purchase
(as a collection) in my Entity Framework project. 我在我的Entity Framework项目中添加了
Customer
到Purchase
(作为集合)的导航属性。 The relationship already existed before, so no database migration is performed. 该关系之前已存在,因此不执行数据库迁移。
When I retrieve a non-empty set of Product
- which also has a navigation property to Purchase
(as a collection) - from the context, I get the following exception: 当我检索一个非空的
Product
集合 - 它也有一个导航属性为Purchase
(作为集合) - 从上下文中,我得到以下异常:
The 'BrandID' property on 'BrandedProduct' could not be set to a 'null' value.
'BrandedProduct'上的'BrandID'属性无法设置为'null'值。 You must set this property to a non-null value of type 'System.Int32'.
您必须将此属性设置为类型为“System.Int32”的非null值。
Simplified code (all entities also have an ID property and a protected/public empty constructor): 简化代码(所有实体也有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...
}
The Purchase
class has a composite primary key, so the following configuration is set up in the DataContext class. Purchase
类具有复合主键,因此在DataContext类中设置了以下配置。
public class DataContext : DbContext {
protected override void OnModelCreating(DbModelBuilder builder) {
builder.Entity<Purchase>().HasKey(x => new { x.CustomerID, x.ProductID });
}
}
Any idea why this could happen? 知道为什么会这样吗?
In this example, it looks like the problem is due to BrandedProduct
not having a primary key which is required by Entity Framework. 在此示例中,问题似乎是由于
BrandedProduct
没有Entity Framework所需的主键。 It is attempting to figure out and set BrandID
as the primary key, which has a private setter. 它试图找出并设置
BrandID
作为主键,它有一个私有的setter。
To solve this, just add the [Key]
attribute or another HasKey
to your configuration for a property with a public setter. 要解决此问题,只需将
[Key]
属性或其他HasKey
到具有公共设置器的属性的配置中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.