实体框架和(1对多) - (多至1)(1 - * * - 1)关系 [英] Entity Framework and (1 to many)-(many to 1) (1 - * * - 1) relations

查看:140
本文介绍了实体框架和(1对多) - (多至1)(1 - * * - 1)关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

荫有些麻烦了一段时间弄清楚如何从数据表中取数据(MSSQL 2008)。问题是这样的。你有3个表:

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(职位):作业ID,作业名

  • TABLE2(工人):WorkerID,WorkerName

  • 表3(Worker2Job)的RowID,WorkerID,作业ID

我假定作业可以通过许多工人来完成,所以我需要Worker2Job表。因此,我可以键入作业ID:1被WorkerID1和WorkerId2等作出...

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...

现在使用实体框架,我不知道如何在第一工人(也没有工人的任何其他列表)取WorkerName属性。

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

任何想法?!
Thx提前!

Any ideas ?! Thx in advance!

推荐答案

您不需要任何特殊的的RowId Worker2Job 。只要定义你的 Worker2Job 只有两列: WorkerId 的JobId 并表这两列复合主键。一旦你将所有三个表到实体设计者将自动看到许多一对多的关系,并在模型中正确的关系仅创建两个实体。 工人实体将拥有工作导航属性和工作将有导航属性。您将能够写这样的查询:

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.

这篇关于实体框架和(1对多) - (多至1)(1 - * * - 1)关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆