简体   繁体   中英

Entity Framework and (1 to many)-(many to 1) (1 - * * - 1) relations

Iam have some trouble for some time to figure out how to take data from a data table (MSSQL 2008). Problem is this. You have 3 tables:

  • TABLE1 (Jobs): JobID, JobName
  • TABLE2 (Worker): WorkerID, WorkerName
  • TABLE3 (Worker2Job): RowID, WorkerID, JobID

I Assume that JOB can be done by many workers, so I need "Worker2Job" table. So I can type that JobID:1 is made by WorkerID1 and WorkerId2 etc...

Now using Entity framework I dont know how to fetch the "WorkerName" property for the first of worker (nor any other list of workers).

Any ideas?! Thx in advance!

You don't need any special RowId in Worker2Job . Just define your Worker2Job with only two columns: WorkerId and JobId and make both these columns composite primary key of the table. Once you add all three tables to the entity designer it will automatically see many-to-many relation and create only two entities with the correct relation in the model. Worker entity will have Jobs navigation property and Job will have Workers navigation property. You will be able to write query like:

var query = context.Jobs.Include("Worker").Where(j => j.JobId == someId);

Such query will load a job with all related workers and you will have access to their names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM