【问题标题】:Only parameterless constructors and initializers are supported in LINQ to Entities?LINQ to Entities 中仅支持无参数构造函数和初始化程序吗?
【发布时间】:2013-03-13 10:33:51
【问题描述】:

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

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

谁能帮忙解释/解决这个问题?

【问题讨论】:

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


    【解决方案1】:
    var products = (from p in db.GetAll()
                   select new ProductViewModel{
                       ID = p.Id,
                       ....
                   });
    

    【讨论】:

    • 这不是很干,因为我将不得不这样做 sn-p 大约 45 次以上,为什么它不能通过 ctor 工作?有其他选择吗?
    • LINQ 需要一个无参数构造函数,因为它想要使用集合初始化({} 括号)。您可以拥有其他类构造函数,但 LINQ 不会使用它们。如果 sn-p 需要重用,为什么不放入一个可重用的函数呢?
    【解决方案2】:

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

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

    【讨论】:

    • 您能详细说明一下吗?我正在尝试将 X 数量的 Product 对象解析为 X 数量的 ProductViewModel 对象。
    猜你喜欢
    • 1970-01-01
    • 2014-07-17
    • 2015-07-31
    • 2013-06-26
    相关资源
    最近更新 更多