我有一个ProductViewModel在运行时转换DTO(产品)。LINQ to Entities只支持无参数的构造函数和初始值设定项吗?
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
有人可以帮助解释/解决这个问题吗?
这不是很干,因为我将不得不做约45+倍片断,它为何不通过正常工作的所有细节构造函数?有没有其他选择? – Smithy 2013-03-13 10:44:15
LINQ需要一个无参数的构造函数,因为它想使用集合初始化('{}'方括号)。你可以有额外的类构造函数,但LINQ不会使用它们。如果片段需要重用,为什么不放入可重用的函数? – Flater 2013-03-13 10:52:46