views:

88

answers:

2

Let's say I have a Person class and an Order class, with foreign keys in the DB. The EF model will mark Person with a List of Orders and Order with a Person instance.

If I want to set the Person for the Order, do I really have to do it with an instance of Person?

Is there not a slimmed down way to do so, say with just a PersonID ?

+3  A: 

To assign Person entity to a Order without loading Person entity, you have to do something like this:

var db = new OneToManyEntities();  
var Order  = new Order { OrderId = 100, OrderName = "Order name" };  
Order. PersonReference.EntityKey = new EntityKey("OneToManyEntities.Person ","PersonID",10);
db.AddToOrders(Order); 
db.SaveChanges();
Puzzled
+2  A: 

Puzzled's answer is correct for EF v1. It's a pain. If you don't mind the extra query, you can set the property succinctly:

int id = 1;
Order.Person = context.Persons.Where(x => x.PersonID == id).FirstOrDefault();

Entity Framework v4 will have "FK Associations", which is a fancy term for directly-settable foreign keys.

Dave Swersky