LinqToEntities and Foreign Keys

I'm trying to use LinqToEntities and just noticed that there are no foreign key fields in the data model. This causes certain problems when trying to add an entry.

Reading around I found that when adding a record, you can do something like this (the product has a foreign key in 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 actually my question is, how does this work in LinqToEntities? It seems to me that this is much more complicated than just giving it a foreign key (i.e. MyProduct.CategoryID = categoryid).

If I have 5 foreign keys in a table, would I need to restore 5 objects in order to relate them?

I see how doing the above might make sense and have advantages, but I see no advantage if you are just trying to add 1 record to a database with one foreign key in another table.

0


source to share


1 answer


For those new to Linq To Entities and wondering the same thing as me ... yes, that's exactly how Linq To Entities is. You should be referring to the actual object, not just a foreign key input.



I think this will be bad for performance, but from what I've done so far, the performance is not bad. It was actually better than Linq To SQL.

+1


source







All Articles