Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting single column from an entity

Tags:

c#

nhibernate

How can you get a single column back from a query instead of a whole object?

I could do something like this to get the whole object, but all I want is the names:

IList<Tribble> tribbles = session.CreateCriteria(typeof(Tribble)).List<Tribble>();
IList<string> names = new List<string>();
foreach (Tribble t in tribbles) {
    names.Add(t.Name);
}

I would like to be able to specify additional criteria, so is it possible to just exclude certain columns from being retrieved?

like image 944
Kevin Albrecht Avatar asked Jul 02 '09 17:07

Kevin Albrecht


People also ask

How do I get a single column value in Entity Framework?

You could use the LINQ select clause and reference the property that relates to your Name column. Show activity on this post. If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.

How do I get specific columns in Entity Framework?

In Entity Framework Core we can select specific columns by using either anonymous types or DTOs.

How do I select a single column in LINQ?

var Q1 = (ds. Tables[1]. AsEnumerable() .


1 Answers

Here is the solution I eventually ended up using:

ICriteria c = session.CreateCriteria(typeof(Tribble));
c.SetProjection(Projections.ProjectionList().Add(Projections.Property("Name")));
IList<string> names = c.List<string>();

I got this idea from this old StackOverflow question.

like image 81
Kevin Albrecht Avatar answered Oct 15 '22 22:10

Kevin Albrecht