简体   繁体   English

实体框架和 (1 to many)-(many to 1) (1 - * * - 1) 关系

[英]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).一段时间以来,我在弄清楚如何从数据表中获取数据时遇到了一些麻烦(MSSQL 2008)。 Problem is this.问题是这样的。 You have 3 tables:您有 3 张桌子:

  • TABLE1 (Jobs): JobID, JobName表 1(作业):作业 ID、作业名称
  • TABLE2 (Worker): WorkerID, WorkerName表 2(工人):工人 ID、工人名称
  • TABLE3 (Worker2Job): RowID, WorkerID, JobID表 3 (Worker2Job):RowID、WorkerID、JobID

I Assume that JOB can be done by many workers, so I need "Worker2Job" table.我假设 JOB 可以由许多工人完成,所以我需要“Worker2Job”表。 So I can type that JobID:1 is made by WorkerID1 and WorkerId2 etc...所以我可以输入 JobID:1 是由 WorkerID1 和 WorkerId2 等创建的......

Now using Entity framework I dont know how to fetch the "WorkerName" property for the first of worker (nor any other list of workers).现在使用实体框架,我不知道如何为第一个工作人员(也不是任何其他工作人员列表)获取“WorkerName”属性。

Any ideas?!有任何想法吗?! Thx in advance!提前谢谢!

You don't need any special RowId in Worker2Job .您在Worker2Job中不需要任何特殊的RowId Just define your Worker2Job with only two columns: WorkerId and JobId and make both these columns composite primary key of the table.只需用两列定义您的Worker2JobWorkerIdJobId ,并使这两列成为表的复合主键。 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.将所有三个表添加到实体设计器后,它将自动查看多对多关系,并在 model 中仅创建两个具有正确关系的实体。 Worker entity will have Jobs navigation property and Job will have Workers navigation property. Worker实体将具有Jobs导航属性,而Job将具有Workers导航属性。 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.这样的查询将加载所有相关工作人员的工作,您将可以访问他们的姓名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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