使用实体框架选择多个列 [英] Select multiple columns using Entity Framework

查看:61
本文介绍了使用实体框架选择多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许是一个简单的问题,但找不到它很容易,所以请原谅我=)
我尝试选择多个列。我使用的语句是:

Maybe an easy question, but can't find it easily so forgive me =) I try to select multiple columns. The statement I use is:

var dataset2 = from recordset in entities.processlists 
               where recordset.ProcessName == processname 
               select recordset.ServerName, recordset.ProcessID, recordset.Username;

很明显,这甚至无法编译。正确的语法是什么?
我也尝试过基于方法,即使这种语法似乎正确,在访问它时也会抛出无法将类型Anonymous type强制转换为AIM.PInfo类型。

Obviously, this doesn't even compile. What is the correct syntax? I also tried method based, and even tough this syntax seems correct, when accessing it throws an 'Unable to cast the type 'Anonymous type' to type 'AIM.PInfo'. LINQ to Entities only supports casting EDM primitive or enumeration types.' exception.

任何想法吗?

var dataset = entities.processlists
             .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
             .Select(x => new { x.ServerName, x.ProcessID, x.Username })
             .Cast<PInfo>().ToList();


推荐答案

实际上,编译器不知道如何转换这种匿名类型( new {x.ServerName,x.ProcessID,x.Username} 部分)到PInfo对象。

Indeed, the compiler doesn't know how to convert this anonymous type (the new { x.ServerName, x.ProcessID, x.Username } part) to a PInfo object.

var dataset = entities.processlists
    .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
    .Select(x => new { x.ServerName, x.ProcessID, x.Username }).ToList();

这为您提供了以后可以使用的(匿名类型)对象列表,但是您可以

This gives you a list of objects (of anonymous type) you can use afterwards, but you can't return that or pass that to another method.

如果您的PInfo对象具有正确的属性,则可能像这样:

If your PInfo object has the right properties, it can be like this :

var dataset = entities.processlists
    .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
    .Select(x => new PInfo 
                 { 
                      ServerName = x.ServerName, 
                      ProcessID = x.ProcessID, 
                      UserName = x.Username 
                 }).ToList();

假定PInfo至少具有这三个属性。

Assuming that PInfo has at least those three properties.

两个查询都允许您仅获取所需的列,但是使用现有类型(如第二个查询中的类型)可以将数据发送到应用程序的其他部分。

Both query allow you to fetch only the wanted columns, but using an existing type (like in the second query) allows you to send this data to other parts of your app.

这篇关于使用实体框架选择多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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