通用方法和 Entity Framework

Generic methods and Entity Framework

我有一些特定于客户的实体,因此我经常想要获取适用于特定客户的实体集。类似于以下内容:

interface IClientSpecific
  int ClientId {get;}

class Entity1 : IClientSpecific
{
 ...
}

class Entity2: IClientSpecific
{
 ...
}

class MyContext : DbContext
{
  DbSet<Entity1> Entity1s {get; set;}
  DbSet<Entity2> Entity2s {get; set;}
}

替换大量重复代码,例如

GetEntity1s(int clientId)
{
  Entity1s.Where(e => e.ClientId);
}

我尝试添加扩展方法:

IQueryable<T> GetForClient<T>(this IQueryable<T> items, int clientId)
  where T : IClientSpecific
{
  return items.Where(i => i.ClientId = clientId);
}

这惨败:

A first chance exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

Additional information: Unable to cast the type 'Entity1' to type 'IClientSpecific'. LINQ to Entities only supports casting EDM primitive or enumeration types.

如何在多个实体类型上重用逻辑?

在扩展方法中添加class泛型类型约束,它可能会解决问题。它对我有用。

IQueryable<T> GetForClient<T>(this IQueryable<T> items, int clientId)
 where T : **class**, IClientSpecific
{
  return items.Where(i => i.ClientId = clientId);
}