这是我的 MySQL 数据库的简化模型(模型优先):
我通过 Entity Framework v6.1.3 映射了它。我有 dataContext
对象来进行数据库查询。
OrderProductsProduct1
是建立外键连接的表,这里是 EF 自动生成的类:
public partial class OrderProductsProduct1
{
public int ID { get; set; }
public int OrderProductsID { get; set; }
public int Product1ID { get; set; }
public decimal Width { get; set; }
public virtual OrderProducts OrderProducts { get; set; }
public virtual Product1 Product1 { get; set; }
}
我很困惑如何将新对象添加到具有两个一对多外键的数据库中。例如,如何通过 OrderProducts
和 OrderProductsProduct1
表正确添加具有少量 Product1
对象的 Order
对象。
到目前为止,我一直在尝试制作一个包含 OrderProducts
的 List
,其中每个 OrderProduct
都有另一个 List
OrderProductsProduct1 和 2
。我向 OrderProductsProduct1 和 2
添加了 Products1 和 2
。最后 OrderProducts
被绑定(bind)到 Order
与 orderProducts.Order = newOrder
然后 dataContext.Add(newOrder)
。但这会导致 Entity Framework 异常。
我是否必须从最低级别(Client、Product1、Product2)创建对象,使用 dataContext.Add()
将它们添加到数据库,以获取它们的 ID,然后将它们与更高级别绑定(bind)对象 (Order) 等等,直到最高级别(OrderProductsProduct1 和 2)?这种方法省略了 Entity Framework ,并且在出现错误时很难恢复更改。
最佳答案
Entity Framework 足够智能,可以查看对象的主键 (ID) 以确定是否必须将其添加为新对象,或者仅使用对象的外键。
假设您要添加一个新的 OrderProductProducts1 以及一个现有的 OrderProducts 和一个现有的 Product1。代码可能如下所示:
Product1 existingProduct = dbContext.Product1s...
OrderProducts existingorderProduct = dbContext.OrderProducts...
使用现有项目 ID 的方法:
OrderProductProducts1 addedProduct = dbContext.OderProductProducts1.Add(
new OperProductProducts1()
{
// don't fill ID, will be filled during SaveChanges
OrderProductsId = existingOrderProduct.ID,
Product1Id = existingProduct.ID,
...
});
除了填写现有项目的 ID,您还可以使用完整的现有项目:
OrderProductProducts1 addedProduct = dbContext.OderProductProducts1.Add(
new OperProductProducts1()
{
// don't fill ID, will be filled during SaveChanges
OrderProducts = existingOrderProduct,
Product1 = existingProduct,
...
});
Entity Framework 足够智能,可以检查现有项目的 Id 以确定是否必须添加它们。
如果您的 OrderProductProducts1 不使用现有项目而是使用现在的项目,只需将它们分配为现有项目即可:
var nonExistingProduct = new Product1s() {...};
// note: because it does not exist ID == 0
OrderProductProducts1 addedProduct = dbContext.OderProductProducts1.Add(
new OperProductProducts1()
{
// don't fill ID, will be filled during SaveChanges
OrderProductsId = existingOrderProduct.Id,
Product1 = nonExistingProduct,
...
});
在 SaveChanges 期间, Entity Framework 看到 nonExistingProduct 的 ID 为零,因此知道必须添加它。产品的 ID 将是国外的 Product1Id。
如果需要,您可以在添加 OrderProductProducts1 之前自行将新产品添加到 DbContext。但是,请记住,只要您没有 SaveChanges,就不能使用 ID:
var justAddedProduct = dbContext.Products.Add(new Product1s() {...});
// note: because it does not exist ID == 0
OrderProductProducts1 addedProduct = dbContext.OderProductProducts1.Add(
new OperProductProducts1()
{
// don't fill ID, will be filled during SaveChanges
OrderProductsId = existingOrderProduct.Id,
Product1 = justAddedProduct,
...
});
关于c# - Entity Framework - 如何将复杂对象添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41251369/