Search code examples
entity-frameworkentity-framework-6.1

Generic methods and Entity Framework


I have some entities that are client-specific, hence I frequently want to get the set of entities that apply to a particular client. Something like the following:

interface IClientSpecific
  int ClientId {get;}

class Entity1 : IClientSpecific
{
 ...
}

class Entity2: IClientSpecific
{
 ...
}

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

To replace a ton of repetitive code like

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

I tried to add extension methods:

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

This fails miserably:

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.

What can I do to reuse logic on multiple entity types?


Solution

  • Add class generic type constraint to the extension method, it might solve the problem. It worked for me.

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