Smithy
Smithy

Reputation: 2190

Only parameterless constructors and initializers are supported in LINQ to Entities?

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?

Upvotes: 0

Views: 1390

Answers (2)

Sandy
Sandy

Reputation: 2449

To retrieve all details from single entity use this

Context.Set<your entity>().AsQueryable();

Upvotes: 0

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

var products = (from p in db.GetAll()
               select new ProductViewModel{
                   ID = p.Id,
                   ....
               });

Upvotes: 0

Related Questions