1

我有这样的对象。

public class BaseTable
{
    public int ID               { get; set; }
    public int ParentID         { get; set; }
    public string Description   { get; set; }
    public bool IsActive        { get; set; }    

}

public class CarFuelType : BaseTable
{

}

和一个测试班

public class Test
{
    public IList<CarFuelType> GetAllActiveFuelTypes()
    {
        var result = GetAllActiveData<CarFuelType>(LookUpTableConstants.CarFuelType);

        return result.Cast<CarFuelType>().ToList(); 
    }


    private IList<T> GetAllActiveData<T>(int filter)
    {
        var result = from c in _lookUpTableValuesRepository.GetAllRowsWhere(l => l.ParentID == filter && l.IsActive==true)
                     select new BaseTable{ ID = c.ID, Description = c.Description, ParentID = c.ParentID };
        return result.ToList() as IList<T>;
    }

}

但我得到从 GetAllActiveData 方法返回的空结果。无论如何我将 IList 从一种类型转换为另一种类型。

4

1 回答 1

6

您在这里遇到了问题,因为您实际上并没有创建派生类的任何实例。您需要实际创建实例CarFuelType而不是BaseTable. 完成此操作后,您将不需要任何铸造。您可以这样做 - 至少对于 LINQ to Objects:

private IList<T> GetAllActiveData<T>(int filter) where T : BaseTable, new()
{
    var result = from c in _lookUpTableValuesRepository
                               .GetAllRowsWhere(l => l.ParentID == filter 
                                                && l.IsActive==true)
                 select new T() { ID = c.ID, 
                                  Description = c.Description,
                                  ParentID = c.ParentID };
    return result.ToList();
}

我怀疑这是否适用于 LINQ to SQL 或实体框架...您可能必须在 LINQ to SQL 查询中创建 BaseTable 的实例,然后将它们转换到内存中,例如

    var baseQuery = from c in _lookUpTableValuesRepository
                               .GetAllRowsWhere(l => l.ParentID == filter 
                                                && l.IsActive==true)
                 select new BaseTable { ID = c.ID, 
                                        Description = c.Description,
                                        ParentID = c.ParentID };

    var converted = baseQuery.AsEnumerable()
                             .Select(b => new T() { ID = b.ID, 
                                                    Description = b.Description,
                                                    ParentID = b.ParentID };

但是,这可能会失去“实体性”-使用这些对象进行更新等时可能会遇到问题。

于 2009-11-15T09:06:00.197 回答