Relationships in Entities as not as obvious as they are in Linq-to-SQL
Despite my
reluctance to step into the darkside of L2E,
I decided that my current project I am forcing myself to use it.
It is bound to be (as it has already proven) frustrating and painful, but I think it's a good idea
to learn.
First problem I have run into is inserting records with relationships.
In L2S, it is very simple and the syntax could not be easier.
If I have a record, and it has a relation to a table of cities, I could simply make a new 'record' and set the 'city_id' to the integer primary key of the city table:
linq-to-sql
record r = new record() { city_id = 5 };
But, with L2E, it is not that simple. In the past, I had shown how to
relate a record using a full trip to the server to get the entire entity;
but that is not efficient and/or the right way to do it.
Now why we can't do something more similar to above will hopefully be covered in the next release, but here is
as close as I can seem to get the syntax:
linq-to-entities
record r = new record();
r.cityReference.EntityKey = new EntityKey(
"YourEntitiesNamespace.cities", "city_id", 5);
Now, this is not nearly as clean as the L2S, but it does not require a trip to the db and isn't too bad.
You will notice that the record has a property 'cityReference' - this is automatically made by the edmx because there is a foreign key reference in the table from record->cities.
Then the new EntityKey just takes in 3 parameters (it is overloaded with other ways to input as well):
- string qualifiedEntitySetName which will be your entityNameSpace.TableName
- string keyName your primary key field
- object keyValue the value in the primary key field