Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 optional one way relation

I have two tables:

Client
------------------------
Id           (string) <-- PrimaryKey
Name         (string)
Number       (int)

Department:*
------------------------
Id           (int) <-- Primary key
Name         (string)
ClientNumber (int?)
Client       (Client, virtual)
.....

Now I want to create an optional relationship from Departmant to Client (using ClientNumber). I've created a virtual property in the Department class (Client) and now I need to configure the relation using EntityTypeConfiguration.

There are no foreign keys configured in the database and I'm not able to change the database. I can't change the Entity (class) Client either.

So I need to tell EntityFramework that the ClientNumber in the Department class is related (optionally) to the Number property in the Client class.

But I can't figure out how to tell EF that the Department's ClientNumber is related to the Client's Number property, not the Client's primary key. (without changing the Client entity class)

edit: The Number property on Client is unique for each entry.

The relation should result in a sql statement like this:

SELECT .....
FROM Department D LEFT OUTER JOIN Client C ON (D.ClientNumber = C.Number)

It's easy to do this using joins in Linq, but it would be great to just:

dbContext.Departments.Include(d => d.Client) 

using a virtual property on Department class containing the Client (if any)

like image 830
stian.net Avatar asked Oct 02 '15 07:10

stian.net


1 Answers

As @Gert Arnold Mentioned this is not "yet" possible . Entity Framework 7 will support this Feature.

For those who want to be kept up to date, here is the Feature Discussion / Voting.

Unique Constraint (i.e. Candidate Key) Support

like image 195
Anestis Kivranoglou Avatar answered Nov 18 '22 13:11

Anestis Kivranoglou