本文介绍了投影在LINQ to SQL和LINQ到实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图动态获取列。在NHibernate的,我可以做到这一点:

I am trying to get the columns dynamically. In NHibernate i can do this:

var list = _session.CreateCriteria(typeof(Person))
                   .SetProjection(Projections.ProjectionList()
                   .Add(Projections.Property("FirstName"))
                   .Add(Projections.Property("LastName"))
                   .Add(Projections.Property("Jersey"))
                   .Add(Projections.Property("FortyYard"))
                   .Add(Projections.Property("BenchReps"))
                   .Add(Projections.Property("VertJump"))
                   .Add(Projections.Property("ProShuttle"))
                   .Add(Projections.Property("LongJump"))
                   .Add(Projections.Property("PersonSchoolCollection"))
                    )
                   .SetResultTransformer(new NHibernate.Transform.AliasToBeanResultTransformer(typeof(Person)))
                   .List<Person>();



什么是LINQ的等价?

What is the equivalent in Linq?

推荐答案

你还标记的和的我假定你正在寻找在LINQ到SQL或实体框架等效。这两个答案(到目前为止)是这种等价物,如果 _session.Query<人>() context.Persons 。 (虽然大流士的回答会抛出一个异常,说,你不能创建一个实体查询实体实例)。

As you also tag linq-to-sql and linq-to-entities I assume you are looking for an equivalent in Linq-to-Sql or Entity Framework. The two answers (so far) would be such equivalents if _session.Query<Person>() were replaced by context.Persons. (Although Darius's answer would throw an exception saying that you can't create entity instances in an entity query).

但除了可能使用的建立一个特设投影,人们的中的新功能使得它更容易。 Automapper是绘制一个非常受欢迎的工具(比如:项目)的类型的类型另一个列表清单。但是直到最近它的缺点是,它只是工作在内存中的列表,即投影没有传播到SQL查询。因此它不能被用来切回查询字段数(如NHibernate的突起那样)

But apart from the possibility to use Select to create an ad hoc projection, one of the newer features of AutoMapper makes it even easier. Automapper is a very popular tool to map (say: project) a list of types to another list of types. But until recently its drawback was that it only worked on in-memory lists, i.e. the projection did not propagate into the SQL query. So it could not be used to cut back the number of queried fields (as NHibernate projections does).

这个问题已在(标题使用AutoMapper说,这一切)。但它也提供了一个初步的,但极好的修复,后来被Automapper自己通过

This problem was described in Stop using AutoMapper in your Data Access Code (the title says it all). But it also offered a preliminary but excellent fix, which was later adopted by Automapper itself.

此功能可以写得很简洁的代码,如:

This feature makes it possible to write very succinct code like:

var dtoList = context.Persons.Project().To<PersonDto>();



(后Person和PersonDto之间的映射Automapper登记)。

(after the mapping between Person and PersonDto was registered in Automapper).

现在SQL查询只包含用于PersonDto的字段。

Now the SQL query only contains the fields that are used for PersonDto.

这篇关于投影在LINQ to SQL和LINQ到实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:48