0

This is the error I'm receiving:

Message = "Unable to cast the type 'App.Models.Subject' to type 'App.Context.ITenantData'. LINQ to Entities only supports casting EDM primitive or enumeration types."

In an attempt to implement multi-tenancy in my application, I added a Tenants table and linked every tenant-specific model to a Tenant (including Subjects).

I got a lot of help from this post: DbSet, ModelBuilder, and EF Navigation Properties

But now I'm stuck with the above casting issue.

My TenantContext:

 public class TenantContext : DbContext {

    private readonly RealContext _realContext;
    private readonly Tenant _tenant;

    public TenantContext(Tenant tenant)
        : base("name=DefaultConnection") {
        this._tenant = tenant;
        this._realContext = new RealContext();
    }

    // _realContext.Subjects is a DbSet
    public IQueryable<Subject> Subjects { get { return FilterTenant(_realContext.Subjects); } }

    private IQueryable<T> FilterTenant<T>(IQueryable<T> values) where T : ITenantData
    {
        return values.Where(x => x.TenantId == _tenant.TenantId);
    }
 }

With ITenantData:

 public interface ITenantData {
    int TenantId { get; set; }
}

And Subject implements ITenantData with a TenantId property:

    [ForeignKey("Tenant")]
    public int TenantId { get; set; }

Now, when I query using TenantContext, I get the above error:

 using (var db = CreateContext()) {   // returns tenantContext
            var dbSubjects = db.Subjects;
            var subjects = dbSubjects.ToList(); // error occurs here

What am I doing wrong?

Also - I'm pretty new to this, so if I'm missing anything critical here, let me know and I'll post up. Thank you for any help you can provide.

Community
  • 1
  • 1
SB2055
  • 10,654
  • 29
  • 87
  • 185

2 Answers2

1

Updating my TenantContext to include class fixed the problem, but I don't know why:

private IQueryable<T> FilterTenant<T>(IQueryable<T> values) where T : class, ITenantData
{
    return values.Where(x => x.TenantId == _tenant.TenantId);
}

If anyone wants to write up anything about the reasoning behind this, I'll gladly accept your answer.

SB2055
  • 10,654
  • 29
  • 87
  • 185
  • This works: private IQueryable FilterTenant(IQueryable values) { return values.Where(x => x.TenantId == _tenant.TenantId); } does it solve the problem? – LINQ2Vodka Nov 05 '13 at 05:11
-1

Here:

values.Where(x => x.TenantId == _tenant.TenantId);  

translator doesnt have an idea how to translate _tenant.TenantId into SQL

LINQ2Vodka
  • 2,783
  • 23
  • 40