谁能告诉我我做错了什么?
当它到达db.SaveChanges()时,我收到以下错误。
在模型生成期间检测到一个或多个验证错误:EntityType' Order'没有定义键。定义此EntityType的键。 Orders1:EntityType:EntitySet' Orders1'是基于类型'订单'没有定义键。
正如你所看到的,我并不想做任何复杂的事情,但是,我看不出我错过了什么。
Db背景:
public class NewOrderContext : DbContext
{
public DbSet<NewServices.OrderEntity> Orders { get; set; }
public DbSet<NewServices.OrderLineEntity> OrderLines { get; set; }
}
OrderEntity:
[Table("Order")]
public class OrderEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int State { get; set; }
public decimal Handling { get; set; }
public int BuyerId { get; set; }
public string ShippingAddresseeName { get; set; }
public string ShippingAddressLine1 { get; set; }
public string ShippingAddressLine2 { get; set; }
public string ShippingCity { get; set; }
public string ShippingRegion { get; set; }
public string ShippingCountry { get; set; }
public string ShippingPostalCode { get; set; }
public DateTime Created { get; set; }
public string TrackingRef { get; set; }
public int OfferId { get; set; }
public virtual ICollection<OrderLineEntity> OrderLines { get; set; }
}
OrderLineEntity:
[Table("OrderLine")]
public class OrderLineEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string PartCode { get; set; }
public decimal PartPrice { get; set; }
public int OrderId { get; set; }
[ForeignKey("OrderId")]
public virtual Order Order { get; set; }
}
我在以下方法片段中使用上述内容:
using (var db = new NewOrderContext())
{
var order = new OrderEntity
{
OfferId = offerId,
....
Created = DateTime.UtcNow
};
var lines = new List<OrderLineEntity>
{
new OrderLineEntity
{
PartCode = offer.PartCode,
PartPrice = offer.PriceOffered
}
};
order.OrderLines = lines;
db.Orders.Add(order);
db.SaveChanges();
......
}