5

I want to create a new row in my database on a table that has a couple of foreign key relationships and I haven't been able to get a handle on what order and what calls need to be made. This is what I have so far:

db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.CustomerReference.Attach( ( from c in db.Customer where c.Id == custId select c ).First() );
db.SaveChanges();

The code is failing on the second line there, saying:

Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached.

Any ideas?

3 Answers 3

8

(Thanks John for the grammar fixes)

So I figured it out. This is what you have to do:

db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.Customer = (from c in db.Customer where c.Id == custId select c).First();
db.SaveChanges();

I hope that helps people.

Sign up to request clarification or add additional context in comments.

Comments

6

Why not use entity references? Your method will cause an extra SELECT statement.

A much nicer way is to use the CustomerReference class and an EntityKey.

order.CustomerReference = new System.Data.Objects.DataClasses.EntityReference<Customers>();
order.CustomerReference.EntityKey = new EntityKey("ModelsEntities.Customers", "Id", custId);

3 Comments

I wouldn't mind using your solution, but I would like to use strongly-typed database column names so I can get compile-time errors if the relationship is invalid.
I agree with kirkmcpherson, his way avoids doing the extra SELECT. I guess you value maintainable code over performance. You can still use his way, but instead of hard coded strings, you can use reflection to generate the strings by getting the class names for ModelsEntities and Customers in the above example. That way you get both one less SELECT, and strong typing / compile time errors. The added overhead from the reflection shouldn't be an issue IMO.
Okay, you can use reflection to generate the Entity Set name but not the Key name (i.e. can generate "ModelsEntities.Customers" using strong typing). Is there a way to generate the "Id" using reflection?
0

For update here is some sample code:

using (var ctx = new DataModelEntities())
{

       var result = (from p in ctx.UserRole.Where(o => o.UserRoleId == userRole.UserRoleId)
                              select p).First();

       result.RolesReference.EntityKey = new EntityKey("DataModelEntities.Roles",
                                       "RoleId", userRole.RoleId);

       result.UserRoleDescription = userRole.UserRoleDescription;      
       ctx.SaveChanges();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.