LINQ to Entities中仅支持无参数构造函数和初始值设定项吗?

时间:2013-03-13 10:33:52

标签: asp.net-mvc entity-framework linq-to-entities

我有一个ProductViewModel,可以在运行时转换DTO(产品)。

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; }
}

之前我已经将这段代码与LINQ2SQL一起使用了,但它现在已经有了,但现在使用实体框架却没有:

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

我收到此错误:

Only parameterless constructors and initializers are supported in LINQ to Entities

有人可以帮忙解释/解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

要从单个实体检索所有详细信息,请使用此

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