master detail / multi table best practice/method Add to Entity Framework

.net entity-framework linq linq-to-entities


This is the format of my table.

Id int identity
OrderDate smalldatetime
OrderStatusid tinyint

Id int identity
Name varchar(50)

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

I'm attempting to insert data using Entity Framework with the following code.
Is this the ideal method for inserting?
I would want to be able to assign a single productId value rather than receiving the whole product item from the context object, which is why I am not satisfied with how I am doing it.

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;

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


Whether there is a better or other technique to complete the master detail insert.

7/21/2009 12:39:03 PM

Accepted Answer

It will be OK to continue as you are.

If you want to allocate ode.Products without doing a database query, you might use the alternate method shown below:

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

Although quicker, this is less readable. Additionally, up until you load it, the Products property will remain null. But this is often acceptable for an insert.

7/21/2009 12:39:13 PM

Popular Answer

An alternative strategy is to utilize Stub Objects rather than EntityKeys, for example.

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

etc. Additionally, in the future, this code will function with POCO objects as well.

For further details on that method, see this article.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow