Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Create navigation property

i created a db-model with the entity framework wizzard in Visual Studio. There are 2 tables (job, stocktype) which are related to each other with the table stocktype2job.

enter image description here

Job <------- no direct relation / navigation property --------> StockType
 |                                                                  |
 |                                                                  |
 ---------------------> StockType2Job ----------------------------->

With a Job Object, i could do something like this ...

EntitiesObject db = new EntitiesObject();
Job job = db.Jobs.SingleOrDefault(j => j.IdJob == 40);

List<StockType> stockTypes = new List<StockType>;
foreach (StockType2Job st2j in job.StockType2Jobs)
    {
        stockTypes.add(st2j.StockType);
    }

That should work just fine. But is there a way to create a navigation property in the job entity so i can write something like this?

EntitiesObject db = new EntitiesObject();
Job job = db.Jobs.SingleOrDefault(j => j.IdJob == 40);

List<StockType> stockTypes = job.StockTypes; // <<-----

Thanks for your kind Help Apo

like image 366
Simon Rossmann Avatar asked Oct 21 '22 22:10

Simon Rossmann


1 Answers

It is clear (from the self reference) that StockType2Jobs does not only contain foreign keys to StockType and Job, so you can't map a many-many relationship with a navigation property job.StockTypes. So you can't do anything else then collecting StockType via job.StockType2Jobs. But that's not a big deal:

List<StockType> stockTypes = job.StockType2Jobs.Select(x => x.StockType);

You might get tempted to wrap this in an unmapped property job.StockTypes, but usually it's not a good idea to do this.

like image 93
Gert Arnold Avatar answered Oct 27 '22 09:10

Gert Arnold