I'm trying to implement EF with an existing table structure that开发者_运维知识库 I'm not allowed to alter to be able to persist data.
I have TableA
with columns like so:
EntityCode
EntityName
...
EntityCode
is the primary key of a table called Entities
with columns like so:
EntityCode
EntityName
The data in memory contains only the EntityCode
for the TableA
record. I need to populate TableA
.EntityName
when inserting the record.
The current code for persistance simply does a lookup first (SELECT EntityName FROM Entities WHERE EntityCode='blah
).
How do I (can I) mimic this behavior in EF 4.1?
Something like this could work:
TableAObject tableA = new TableAObject() { EntityCode = "123" };
//...
using (var context = new MyDbContext())
{
tableA.EntityName = context.Entities
.Where(e => e.EntityCode == tableA.EntityCode)
.Select(e => e.EntityName)
.SingleOrDefault();
context.TableAObjects.Add(tableA);
context.SaveChanges();
}
精彩评论