Where子句使用Expression <func <>&gt;和<t> </t> </func <>

时间:2014-07-23 18:44:24

标签: c# .net linq generics

这是我的代码:

public class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
    public Place place {get; set;}
}

public class Customer : Person
{
    public int Id {get; set;}
    public string CustomerProperty {get; set;}
}

public class Employee : Person
{
    public int Id {get; set;}
    public string EmployeeProperty {get; set;}
}

所以我创建了一个方法来使用linq Where子句按庄园或城市或地点进行过滤。

        public static Expression<Func<Customer, bool>> FilterByPlace(string stateId, string cityId, string placeId)
    {
        if (placeId != null)
        {
            return u => u.PlaceId == placeId;
        }
        else if (cityId != null)
        {
            return u => u.Place.Address.cod_city == cityId;
        }
        else if (stateId != null)
        {
            return u => u.Place.Address.City.cod_state == stateId;
        }

        return u => true;
    }

如果我想为员工执行此操作,我需要复制并将此<Func<Customer>>更改为<Func<Employee>>。有没有办法使用<T>代替我的实体?

当我更改<Func<Person>>的代码时,它返回错误,因为Type与linq表达式上的预期值不同。

var custom = db.Customers
                            .Include(item => item.Place)
                            .Include(item => item.Place.Address)
                            .Include(item => item.Place.Address.City)
                            .Include(item => item.Place.Address.City.State)
                            .Where(item => item.Status == (Status)tableStatus)
                            .Where(FilterByPlace(stateId, cityId, placeId))
                            .OrderByDescending(item => item.CustomerId);

谢谢!

1 个答案:

答案 0 :(得分:2)

尝试使用Person作为通用约束来创建泛型方法。

public static Expression<Func<T, bool>> FilterByPlace<T>(string stateId, string cityId, string placeId) 
   where T : Person
{
    if (placeId != null)
    {
        return u => u.PlaceId == placeId;
    }
    else if (cityId != null)
    {
        return u => u.Place.Address.cod_city == cityId;
    }
    else if (stateId != null)
    {
        return u => u.Place.Address.City.cod_state == stateId;
    }

    return u => true;
}