最佳实践/方法在实体框架主从/多表插入 [英] best practise/way for master detail / multi table Insert in Entity Framework

查看:280
本文介绍了最佳实践/方法在实体框架主从/多表插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表结构是这样的

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

我试图使用实体框架使用下面
的code插入操作 这是做插入的最佳方法是什么?
我是不是能够只分配一个简单的ProductID值

I am trying to an insert operation using Entity Framework using the code below
Is this the best way to do the insert?
I am not happy with the way I am getting the full product item from the context object, instead of being able to just assign a simple productId value

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();
}

这是做主人的细节插入正确的做法还是有一个更好的/另一种方式。

Is this the correct way to do the master detail insert or is there a better/another way.

推荐答案

你在做什么现在的工作就好了。

What you are doing now will work just fine.

如果你想避免分配ode.Products在做一个数据库查询,那么你可以使用以下选择:

If you would like to avoid doing a database query when assigning ode.Products, then you could use the following alternative:

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

这是更快,但不可读性。此外,产品属性将为空,直到您加载它。但是对于一个插入,这往往是行

This is faster, but less readable. Also, the Products property will be null until you Load it. But for an insert, this is often OK.

这篇关于最佳实践/方法在实体框架主从/多表插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆