Entity Framework中实现主从表/多表插入的最佳实践/方法

7

我的表格结构如下

Orders
------ 
Id int identity
OrderDate smalldatetime
OrderStatusid tinyint

Products
--------
Id int identity
Name varchar(50)

OrderDetails
------------
Id int identity
OrderId int (fkey)
ProductId int (fkey)
Amount decimal
Rate decimal

我正在尝试使用以下代码使用Entity Framework进行插入操作
这是最好的插入方法吗?
我不喜欢从上下文对象中获取完整的产品项的方式,而是希望能够只分配一个简单的productId值

using (MyContextEntities ctx = new MyContextEntities())
{
    Orders newOrder = new Orders()
    {
    Name = "Gayle Wynand",
    OrderDate = DateTime.Now,
    IsComplete = true,
    Comments = "test",
    OrderStatusId = 2,
    IsActive = true
    };
    OrderDetails ode = new OrderDetails();
    ode.Products = ctx.Products.First(p => p.Id == 2); // any other way?
    ode.Quantity = 2;
    ode.Rate = 5.2;
    newOrder.OrderDetails.Add(ode);

    OrderDetails ode2 = new OrderDetails();
    ode2.Products = ctx.Products.First(p => p.Id == 3); // any other way?
    ode2.Quantity = 3;
    ode2.Rate =6.5;
    newOrder.OrderDetails.Add(ode2);


    ctx.AddToOrders(newOrder);
    ctx.SaveChanges();
}

这是进行主从插入的正确方式吗?还是有更好/其他的方式。

缺少 AddTo<TableName> ... 谢谢! - nrod
2个回答

2

你现在所做的将完全有效。

如果你想在分配ode.Products时避免进行数据库查询,那么你可以使用以下替代方法:

// substitute your actual qualified entity set name
ode.ProductsReference.EntityKey = 
    new EntityKey("MyEntities.ProductsEntitySetName", "Id", 2);

这种方式速度更快,但可读性较差。同时,如果您不加载它,Products属性将为null。但对于插入操作而言,这通常是可以接受的。


我不确定你的意思。你期望什么样的快捷方式?你能更具体地说明你的需求吗? - Craig Stuntz
我想知道如何执行与上面相同的操作,但是使用更新操作。 - Binoj Antony
因为看起来我需要再次从数据库查询实体,然后更改属性(以更改实体状态),然后执行更新(SaveChanges),有更简单/更容易的方法吗? - Binoj Antony
没错。如果要进行更新,你必须先选择,然后保存。 - Craig Stuntz
如何先调用AcceptChanges,然后更改一个属性,最后再调用SaveChanges()?这样我们就可以避免进行select操作。 - Binoj Antony

1

另一种方法是使用 Stub 对象而不是 EntityKeys,例如:

var product = new Product {ID = 2};
ctx.AttachTo("Products", product);
ode.Product = product;

等等,作为额外的奖励,这段代码将来也能与POCO对象一起使用。

有关该技术的更多信息,请参见此博客文章


我首先尝试了这个,发现当调用ctx.SaveChanges()时,它甚至尝试插入Products。 - Binoj Antony

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接