我有類似下面的一個數據庫:LINQ到實體插入多個子女的關係記錄爲許多一對多關係使用POCO
Order
===============
OrderID
Description
EmployeeID
...other fields
Product
===============
ProductID
...other fields
OrderProducts
===============
OrderID
ProductID
Employee
===============
EmployeeID
...other fields
我使用LINQ到實體和EDMX文件已經創建而沒有OrderProducts表,因爲它只是一個連接表。產品表是靜態產品的列表 - 我目前不需要插入任何行。 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 });
// }
長,所以我不明白 - 爲什麼我要加數據庫對象到我的POCO對象?如何將子關係插入到數據庫中? – JumpingJezza 2012-01-18 02:07:17
如果我將它保留爲IEnumerable並將最後一行更改爲dbOrder.Products.Add(p);有用! :) – JumpingJezza 2012-01-19 01:11:51
@JumpingJezza什麼會添加一個新的'產品'。你不想添加一個'OrderProduct'? – Eranga 2012-01-19 01:27:21