简体   繁体   English

使用LINQ创建具有1:N关系的实体的查询

[英]Create a query using LINQ to entities with 1:N relation

I know it's not something unusual to make such kind of queries but I think I get lost so I seek help. 我知道做出这样的询问并不是不寻常的,但我想我迷路了,所以我寻求帮助。 I have to tables with relation 1:N and to make it more clear I'll post a print screen from the management studio : 我必须使用关系1:N的表格,并使其更清晰我将从管理工作室发布一个打印屏幕:

表关系

I am working on a asp.net mvc 3 project and I need to make a view where all Documents will be shown (and some filter and stuff, but I think that is irrelevant for this case). 我正在开发一个asp.net mvc 3项目,我需要创建一个视图,显示所有Documents (以及一些过滤器和内容,但我认为这与此案例无关)。 I need the data from the table Documents and only one specific record for each document from the DocumentFields table. 我需要来自表Documents的数据,并且只需要DocumentFields表中每个文档的一个特定记录。 This record is the record holding the name of the Document and it's uniqueness is DocumentID == Docmuents.Id, DocumentFields.RowNo == 1 and DocumentsFields.ColumnNo == 2. This is unique record for every Document and I need to get the FieldValue from this record which actually holds the Name of the Document. 此记录是包含Document名称的记录,它的唯一性是DocumentID == Docmuents.Id,DocumentFields.RowNo == 1和DocumentsFields.ColumnNo == 2.这是每个Document的唯一记录,我需要获取FieldValue从该记录中实际保存文件名称。

I am not very sure how to build my query (maybe using JOIN) and I also would like to make my view strongly typed passing a model of type Documents but I'm not sure if it's possible, but I think depending on the way the query is build will determine the type of the model for the view. 我不太确定如何构建我的查询(可能使用JOIN),我也想让我的视图强类型传递类型Documents的模型,但我不确定是否可能,但我认为取决于方式query is build将确定视图模型的类型。

I believe what you want is something like this: 我相信你想要的是这样的:

var results = 
    from d in dbContext.Documents
    join df in dbContext.DocumentFields 
    on new { d.Id, RowNo = 1, ColumnNo = 2 } equals 
       new { Id = df.DocumentId, df.RowNo, df.ColumnNo }
    select new 
    {
        Document = d,
        DocumentName = df.FieldValue
    };

Of course if you set up navigation properties, you can just do this: 当然,如果您设置导航属性,您可以这样做:

var results = 
    from d in dbContext.Documents
    let df = d.DocumentFields.First(x => x.RowNo == 1 && x.ColumnNo == 2)
    select new 
    {
        Document = d,
        DocumentName = df.FieldValue
    };

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

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