Search code examples
c#linqentity-frameworklinq-to-entitiesedmx

In Entity framework load child in parent entity (non primary key association)


I am very new to Entity Framework and so I don't know the technical terms use in it. I am sorry for my bad English.

I am working in a project which has entity framework in it and has an .edmx file. The file has entities created in it.

So I created 2 entities and named it TableA and TableB. pid is entity key of TableA and cid is entity key of TableB . And created many to one relationship in it. i.e. TableA row1 can have TableB_cid=1 TableA row2 can also have TableB_cid=2

And then I did "Generate database from model"

CREATE TABLE [TableA] (
    [pid] nvarchar(max)  NOT NULL,
    [name] nvarchar(max)  NOT NULL,
    [TableB_cid] nvarchar(max)  NOT NULL
);
GO


CREATE TABLE [TableB] (
    [cid] nvarchar(max)  NOT NULL,
    [name] nvarchar(max)  NOT NULL
);

pid|name|TableB_cid
--------------------
1 | a | 2
2 | b | 2
3 | c | 1


cid|name
------------
1 | s
2 | f

Now in the C# code i wrote this,

TableA obj = repository.All().Single(w=>w.pid == "1")
context.Entry<TableA>(obj).Reference<TableB>(o => o.TableB).Load();

Now this will load the TableB whose cid=1 (but what i actually wanted was to load TableB whose cid=2).

I think its matching primary key to primary key and not TableB_cid (TableA) to cid (TableB).

So what i am doing wrong please help.

Edit:
In short I am looking for a way where I can add association of a Non Primary column of table A with a Primary column of table B in Entity Framework 4.0. And I don't want to use linq queries and joins. I have tried but I cant a find a way or option in edmx file where i can do it. enter image description here

enter image description here

enter image description here Thanks,

M


Solution

  • I'm not sure I understand the question, but in your example, are you simply attempting to access the TableB entity of the TableA with Id 1?

    If so, how about this:

    TableA obj = repository.All().Single(w=>w.pid == "1");
    TableB SecondTable = obj.TableB;
    

    SecondTable.cid should be 2, is and obj.pid should be 1. If not, what values are you getting?