5

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try something like this:

 var stocksTypes = from st in db.StockType 
     from stj in st.StockType2Job where stj.Job.IdJob==40 select st;
  • This code is not creating any new navigation property, it just "joining" the tables. I supose that the StockType2Jobs table exists for a good reason.

I recommend you to have a look at how to deal with N to N relationship with EF.

Some links [1] [2]

Hope Helps

1 Comment

no doubt that this would work but i rather dont want to use linq when there is a more elegant way, but thx anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.