2013-03-13 64 views
0

我有一个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 

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

回答

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

这不是很干,因为我将不得不做约45+倍片断,它为何不通过正常工作的所有细节构造函数?有没有其他选择? – Smithy 2013-03-13 10:44:15

+1

LINQ需要一个无参数的构造函数,因为它想使用集合初始化('{}'方括号)。你可以有额外的类构造函数,但LINQ不会使用它们。如果片段需要重用,为什么不放入可重用的函数? – Flater 2013-03-13 10:52:46

0

为了取回单个实体使用本

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

请您详细说明一下吗?我试图将X数量的Product对象解析为X个ProductViewModel对象。 – Smithy 2013-03-13 10:50:03

+0

你检查过了吗? [链接](http://stackoverflow.com/a/3893502/1371631) – Sandy 2013-03-13 11:43:50

相关问题