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

时间:2012-11-25 09:11:17

标签: c# linq linq-to-entities

我不希望每次都初始化每个字段,我想在构造函数中所有的initsilizirovat,有可能吗?

 var districts = _districtRepository.FindBy(d => d.CityID == id).Select(d => new DistrictViewModel(d)).ToList();

模型:

public class DistrictViewModel
{
    public Int32 ID { get; set; }
    public String Name { get; set; }

    public DistrictViewModel()
    {

    }

    public DistrictViewModel(District district)
    {
        if (district != null)
        {
            ID = district.ID;
            Name = district.Name;
        }
    }
}

1 个答案:

答案 0 :(得分:5)

你可以这样做:

var districts = _districtRepository.FindBy(d => d.CityID == id)
                                   .AsEnumerable()
                                   .Select(d => new DistrictViewModel(d))
                                   .ToList();

在这种情况下,您的语句.Select(d => new DistrictViewModel(d))是linq-to-object语句,而不是linq-to-entity,它将起作用。