1

我不想每次都初始化每个字段,我想在构造函数中全部初始化,可以吗?

 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;
        }
    }
}
4

1 回答 1

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,它将起作用。

于 2012-11-25T09:18:29.577 回答