Select multiple columns using Entity Framework

.net c# entity-framework

Question

Maybe a simple question, but I can't seem to find it easily. Please pardon me =) I attempt to choose several columns. The phrase I employ is:

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

This obviously fails to even build. What syntax is appropriate? I also tried method-based, however even though this syntax appears to be fine, accessing it results in an exception that reads, "LINQ to Entities only enables casting EDM primitive or enumeration types."

Any thoughts?

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();
1
53
9/2/2016 2:17:51 AM

Accepted Answer

The compiler, in fact, is unable to convert this anonymous type (thenew { x.ServerName, x.ProcessID, x.Username } to a PInfo object as part).

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 returns a list of objects (of the anonymous type) that you can use later, but you cannot pass it to another method or return it.

Your PInfo object may resemble this if it contains the required properties:

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();

assuming at least those three attributes are present in PInfo.

Both queries let you retrieve just the desired columns, but only the second one lets you communicate the data to other areas of your app because it makes use of an existing type.

100
10/23/2013 8:11:55 AM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow