Skip to main content
 首页 » 编程设计

c#之EF 不同对象的相同位置

2024年02月13日21lexus

看看下面的场景:

 class CompanyDto  { 
     public string Street { get; set;} 
     public int Number { get; set;} 
     public bool IsAttr1 { get; set;} 
     public bool IsAttr2 { get; set;} 
     public bool IsAttr3 { get; set;} 
     // Other not common Properties 
 } 
 
 class AnimalDto { 
     public string Street { get; set;} 
     public int Number { get; set;} 
     // Other not common Properties 
 } 
 
 class HouseDto { 
     public bool IsAttr1 { get; set;} 
     public bool IsAttr2 { get; set;} 
     public bool IsAttr3 { get; set;} 
     // Other not common Properties 
 } 
 
 class PersonDto { 
     public string Street { get; set;} 
     public int Number { get; set;} 
     public bool IsAttr1 { get; set;} 
     public bool IsAttr2 { get; set;} 
     public bool IsAttr3 { get; set;} 
     // Other not common Properties 
 } 

我有这些要从 Entity Framework 上下文中填充的 Dto。问题是我想使用标准 where 子句过滤结果。 示例:

 List<PersonDto> prs = context.Person.Where(x => x.Number == SomeValue && Street == SomeOtherValue).Where( x=> x.IsAttr1 || x.IsAttr2).Select(//projection here).ToList(); 
 
 List<AnimalDto> anmls = context.Animal.Where(x => x.Number == SomeValue && Street == SomeOtherValue).Select(//projection here).ToList(); 
 
 etc. 

我想将它们投影到 Dtos(简单),但我不想一次又一次地编写 Where 子句。我尝试使用扩展方法来做到这一点,但在使用基类(地址和标志)和使用接口(interface)时都失败了,因为 IQuerable 无法从接口(interface)转换为具体类。

有什么办法可以做到这一点吗?

更好的方法是使用这样的扩展方法:

public static IQueryable<IAddress> WhereAddress(this IQueryable<IAddress> qry, int SomeValue, int SomeOtherValue) 
    { 
        return qry.Where(x => x.Number == SomeValue && Street == SomeOtherValue); 
    } 

但是我不能在 WhereAddress 子句和 IQuerable.cast() 之后添加 WhereFlags;无法执行转换。

请您参考如下方法:

您可以按如下方式实现您的扩展方法,并将泛型参数限制为 IAddress 类型和 class (这避免了异常“LINQ to Entities 仅支持转换 EDM 基元或枚举类型”)并在您的类型上实现接口(interface) Company , Animal和 Person

public static IQueryable<TAddress> WhereAddress<TAddress>(this IQueryable<TAddress> qry, int SomeValue, string SomeOtherValue) 
  where TAddress : class, IAddress { 
    return qry.Where(x => x.Number == SomeValue && x.Street == SomeOtherValue); 
} 

有了这个你就可以调用

context.Person.WhereAddress(SomeValue,SomeOtherValue).Where(x=> x.IsAttr1 || x.IsAttr2); 

但不是

context.House.WhereAddress(SomeValue,SomeOtherValue); 

原因House不执行 IAddress .