Philip Stratford
Philip Stratford

Reputation: 4753

Return only specified properties from an Entity Framework class

I'm pretty much brand new to Entity Framework and to ASP.NET MVC (and still learning C#), so please forgive me if some of my terminology isn't right here.

Simply, I have installed Entity Framework in my ASP.NET MVC project which I'm hoping to use to create a Web API to serve up an XML list of records. Entity Framework created my entity classes.

In my controller, I can get an XML list by using this code:

public IEnumerable<Person> GetAllPersons()
{
        IEnumerable<Person> person;

        using (var context = new ContactsContext())
        {
            context.Configuration.ProxyCreationEnabled = false;
            person = context.People.ToList();
        }

        return person;
}

This is great.

However, what if I only want to return certain properties of the Person object? What if I just want, for example, the FirstName and LastName properties?

I've found examples using things like

person = (from p in context.People
          select new { p.FirstName, p.LastName })

But this presents problems. Doing this means that my IEnumerable list is no longer a list of type Person. If I change the type to dynamic it will at least compile, but the problem with that is that it doesn't display in the browser successfully, presumably because the XML deserialiser no longer knows what the structure of the object is.

Is there really no way of just returning certain properties of the object which I specify, whilst still conveying the fact that it is, in fact, a Person object which I'm returning? And, if not, how would I go about just returning certain properties of the object in a format which the browser can interpret as XML?

Upvotes: 0

Views: 1552

Answers (2)

Kahbazi
Kahbazi

Reputation: 15015

you can do this :

List<Person> persons = (from p in context.People
          select new { FName = p.FirstName, LastName = p.LastName })
         .ToList()
         .Select(p=>new person() { FirstName= FName , LastName = LName });

Upvotes: 1

jimmious
jimmious

Reputation: 368

List<Person> person = context.People.AsEnumerable()
                      .Select(o => new Person {
                                       FirstName = o.FirstName , 
                                       LastName = o.LastName 
                      }).ToList();

That way you'll be sure your list is of type Person(since if I understand that is what you need)

*Also you are declaring person as an Enumerable but you are returning a List to it

Upvotes: 0

Related Questions