Engin Ozsozgun
Engin Ozsozgun

Reputation: 47

How to get specific column in Entity Framework

I have a product table. I want to get a specific column (only name and price columns) from this table, but I am getting an error. What am I doing wrong?

To summarize, I want to write

SELECT name, surname 
FROM Product 
WHERE name='emre'

but in my Entity Framework based code.

public class products
{
    public int ID { get; set; }
    public string name { get; set; }
    public decimal price { get; set; }
    public int stock { get; set; }
}

public class EtradeContext:DbContext
{
    public DbSet<products> prdcts { get; set; }
}

My ProductDal.cs is below:

    public List<products> GetNameAndPrice()
    {
        using (EtradeContext context = new EtradeContext())
        {

            var result = (from x in context.prdcts
                          where x.name == "emre"
                          select new products
                          {
                              name = x.name,
                              price=x.price

                          }).ToList();
            return result;
        }
    }

And I am getting this error.

Upvotes: 2

Views: 1082

Answers (3)

Milad
Milad

Reputation: 117

You can try this way too.
It,s clear and optimized.

 using (EtradeContext context = new EtradeContext())
    {

        var result = context.prdcts
            .Where(x => x.name == "emre")
            .Select(s => new
            {
                name = s.name
                ,
                price = s.price
            }).ToList();

        return result;
    }

Upvotes: 0

Anurag Tiwari
Anurag Tiwari

Reputation: 1

Use this code:

public class ProductDTO
{
    public string Name { get; set; }
    public string Price{ get; set; }
}

  public List<ProductDTO> GetNameAndPrice()
    {
        using (EtradeContext db= new EtradeContext())
        {
        return (from p in db.prdcts
            where p.name == "emre"
            select new ProductDTO { Name = p.name,Price = p.price }).ToList();
        }
    }

Upvotes: 0

yannick
yannick

Reputation: 715

You cannot project the result to the same entity. What you can do is to use an anonymous type, something like a DTO, ViewModel or something like this. But using the same class in the select like you have in your DBSet will produce your error:

var result = (from x in context.prdcts
              where x.name == "emre"
              select new ProductDTO
                      {
                          name = x.name,
                          price = x.price
                      }).ToList();

Upvotes: 3

Related Questions