views:

225

answers:

1

I'm trying to use LinqToEntities and just noticed that there are no foreign key fields in the data model. That seems to cause some trouble when trying to add a record.

Reading around I found that when adding a record you can do something like this (Product has a foreign key to the Categories table).

Product myProduct = new Product();
myProduct.ProductName = ProductName;
myProduct.Categories = db.CategorySet.Where(c => c.CategoryID == CategoryID).First();
db.AddToProductSet(myProduct);
db.SaveChanges();

I'm sure there is a better way to do this. But my question is really, is this how it works in LinqToEntities? It seems to me that this is a lot more complicated than simply giving it a foreign key (i.e. myProduct.CategoryID = categoryid).

If I have 5 foreign keys in a table, I'm going to have to retrieve 5 objects in order to link them up?

I can see how doing the above might make sense and have benefits, but don't see the benefit if you are just trying to add 1 record to the database that has a single foreign key in another table.

+1  A: 

For anyone who is new to Linq To Entities and wondered the same thing I did... yes, this is how Linq To Entities is. You need to reference an actual object instead of just giving a foreign key.

Seems to me this would do something bad to performance, but from what I've done so far the performance is not bad at all. Actually it's been better than Linq To SQL.

metanaito