Linq to Entities使用POCO为多对多关系插入多个子关系记录

时间:2012-01-17 09:00:36

标签: c# asp.net entity-framework linq-to-entities many-to-many

我有一个类似于下面的数据库:

Order
===============
OrderID
Description
EmployeeID
...other fields


Product
===============
ProductID
...other fields


OrderProducts
===============
OrderID
ProductID


Employee
===============
EmployeeID
...other fields



我正在使用Linq to Entities,而 edmx文件是在没有OrderProducts表的情况下创建的,因为它只是一个连接表。 Products表是静态产品列表 - 我现在不需要插入任何行。 Order表我可以使用以下代码成功插入行:

[Serializable]
public class MyOrderObject
{
   public int OrderID { get; set; }
   public string OrderDescription { get; set; }
   public int? EmployeeID { get; set; }
   public IEnumerable<MyProductObject> ProductsList { get; set; }
   ...other fields
}

[Serializable]
public class MyProductObject
{
   public int ProductID { get; set; }
   ...other fields
}


private static void AddNewOrder(MyOrderObject order)
{
   using (var context = DatabaseHelper.CreateContext())
   {
      var dbOrder = new Order
      {
         OrderID = order.OrderID,
         Description = order.OrderDescription,
         Employee = context.Employees.SingleOrDefault(x => x.EmployeeID == order.EmployeeID),
      }
      context.AddToOrders(dbOrder);
      context.SaveChanges();
   }
}

如何将数据库中的子关系记录列表插入数据库? 我试过了:

List<int> ProductIDs = order.ProductsList.Select(x => x.ProductID).ToList();
//dbOrder.Products.Attach(context.Products.Where(x => ProductIDs.Contains(x.ProductID)));
//or dbOrder.Products = context.Products.Where(x => ProductIDs.Contains(x.ProductID));
//or dbOrder.Products = context.Products.Contains(ProductIDs);
//or foreach(var p in order.ProductsList)
//   {
//      context.AttachTo("Products", new Product { ProductID = p.ProductID });
//   }

2 个答案:

答案 0 :(得分:2)

您需要将ProductsList类型更改为ICollection。并确保它是EDMX映射模型的一部分。

public class MyOrderObject
{
   public int OrderID { get; set; }
   public string OrderDescription { get; set; }
   public int? EmployeeID { get; set; }
   public ICollection<MyProductObject> ProductsList { get; set; }
   ...other fields
}

然后你可以添加产品

var products = context.Products.Where(/**/);
foreach(var p in products)
   order.ProductsList.Add(p);

答案 1 :(得分:1)

无需更改对象类型:

var dbOrder = new Order
{
   OrderID = order.OrderID,
   Description = order.OrderDescription,
   Employee = context.Employees.SingleOrDefault(x => x.EmployeeID == order.EmployeeID),
}

//this adds the relationship to the child without adding a new child record - perfect!
foreach(var p in order.ProductsList)
{
   dbOrder.Products.Add(p);
}

context.AddToOrders(dbOrder);
context.SaveChanges();