0

I have a ProductViewModel that converts a DTO (Product) at runtime.

public class ProductViewModel : IViewModel {

    public ProductViewModel() {
        Categories = new List<CategoryViewModel>();
    }

    #region DTO Helpers

    public ProductViewModel(Product p) {
        this.ID = p.ID;
        this.Name = p.Name;
        this.Price = p.Price;
        Categories = new List<CategoryViewModel>();
    }

    #endregion


    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public IEnumerable<CategoryViewModel> Categories { get; set; }
}

I've used this code with LINQ2SQL before and it's worked, but now with entity framework it doesn't:

        var products = (from p in db.GetAll()
                        select new ProductViewModel(p));

I get this error:

Only parameterless constructors and initializers are supported in LINQ to Entities

Can anybody help explain/fix this?

Smithy
  • 2,170
  • 6
  • 29
  • 61

2 Answers2

0
var products = (from p in db.GetAll()
               select new ProductViewModel{
                   ID = p.Id,
                   ....
               });
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
  • That's not very DRY since I'm going to have to do that snippet about 45+ times, Why does it not work via the ctor? is there an alternative? – Smithy Mar 13 '13 at 10:44
  • 1
    LINQ needs a parameterless constructor because it wants to use collection initialization (the `{}` brackets). You can have additional class constructors, but LINQ will not use them. If the snippet needs to be reused, why not put in in a reusable function? – Flater Mar 13 '13 at 10:52
0

To retrieve all details from single entity use this

Context.Set<your entity>().AsQueryable();
Sandy
  • 2,429
  • 7
  • 33
  • 63
  • Could you elaborate please? I'm trying to parse X amount of Product objects into X amount of ProductViewModel objects. – Smithy Mar 13 '13 at 10:50