我不希望每次都初始化每个字段,我想在构造函数中所有的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;
}
}
}
答案 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,它将起作用。