我想做一个简单的LINQ 2多对多sql,插入一些数据,操作。问题与Linq2Sql多对多的关系和插入新的对象
这里是代表一个多对多的股票罗斯文模型:
alt text http://www.iaingalloway.com/images/linq-detail.jpg
现在我想要做的是插入一个新的秩序,如果产品不存在,然后插入在同一时间内,在同一交易。我得到的错误是:
System.Data.Linq.DuplicateKeyException: Cannot add an entity with a
key that is already in use.
所以这是我(pseduo)代码:
using (SqlContext db = new SqlContext())
{
// Get existing or create a new instance.
Order newOrder = GetOrder(order.Id) ?? new Order();
// Left to right stuff.
newOrder.Foo = order.Foo;
// Now associate this new order to a product (which might not exist).
if (!order.ProductList.IsNullOrEmpty())
{
// We have some products...
IList<Order_Detail> orderDetailList = new List<Order_Detail>();
foreach(Models.Product product in order.ProductList)
{
// Associate each product to the a new order_detail.
orderDetailList.Add(new Order_Detail
{
Product = new SqlContext.Product
{
Foo = product.Foo
}
});
}
// Now associate all the order_details to this order.
newOrder.Order_Details.AddRange(orderDetailList);
if (newOrder.Id <= 0)
db.InsertOnSubmit(newOrder);
db.SubmitChanges(); // <-- exception throw here.
}
}
我假设我需要先保存的产品我尝试之前,并保存顺序?我很困惑:(
感谢您的链接。您绝对正确的看到M-M在LINQ2SQL中没有(本机)支持,并且1-M:M-1桥是常规方法。不太确定是否有回票。 – 2010-12-29 08:25:49