我想在两个模型和两者的种子值之间创建一对多的关系。虽然我收到一个错误,即 EF 试图将“多”模型转换为集合。两种型号如下:
产品(许多):
public class Product
{
[Key]
public int Id { get; set; }
[Required]
public string ModelNum { get; set; }
[ForeignKey("Id")]
public virtual Market Market { get; set; }
public string Brand { get; set; }
public string Type { get; set; }
public bool IsSuggestedProduct { get; set; }
}
市场(一):
public class Market
{
[Key]
public int Id { get; set; }
public string Code { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
尝试播种:
Market market = new Market() { Code = "US" };
market.Products = new List<Product>()
{
new Product
{
ModelNum = "modelNum1",
Brand = "Brand1",
Market = market,
IsSuggestedProduct = false
},
new Product
{
ModelNum = "modelNum2",
Brand = "Brand2",
Market = market,
IsSuggestedProduct = true,
Type = "Type1"
}
};
context.Markets.AddOrUpdate(m => m.Id, market);
context.SaveChanges();
在“AddOrUpdate”处,我检索到以下错误:
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Unable to cast object of type 'System.Collections.Generic.List`1[TestAPI.Models.Product]' to type 'TestAPI.Models.Product'.
Source=System.Data.Entity
更新:感谢 jure,我删除了 Product 中的“ForeignKey”属性,现在它可以工作了。