2

I understand that I can get a list of records from a specific table like this:

var artists = db.Artists.ToList();

However, I am attempting to create a Validation Factory for many of my Object Classes, I would like to send a string containing the Table Name (with Namespace), then call that table.

I've tried this: Dynamic table name in linq

I have the following in my DbContext:

    public DbSet Set(string name)
    {
        // you may need to fill in the namespace of your context
        return base.Set(Type.GetType(name));
    }

Then I have this (the .Where isn't working):

using (var db = new ApplicationDBContext())
{
    // Since your DbSet isn't generic, you can can't use this:
    // db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
    // Your queries should also be string based.
    // Use the System.Linq.Dynamic nuget package/namespace
    var results = db.Set("x.Models.Music.Artist")
      .AsQueryable()
      .Where("Name != null") //Just an example
      ;

    //Do something to validate
}

I get 'IQueryable' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?)

I'm sure it is a simple fix, but not sure how to resolve at the moment.

Derek
  • 653
  • 7
  • 20
  • which entity framework version are you using? – Lei Yang Jul 07 '17 at 01:38
  • I believe it is 6.1.3 (EntityFramework.6.1.3.nupkg) – Derek Jul 07 '17 at 01:41
  • do you have using System.Data.Entity; using System.Linq – mybirthname Jul 07 '17 at 01:42
  • I have `using System.Linq;`, but didn't have `using System.Data.Entity;`. Added it, still `'IQueryable' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?)` – Derek Jul 07 '17 at 01:45
  • entity framework's advantage is strong type and compile time checking, you're using magic strings so you lose this benefits. so can you consider raw sql statements? – Lei Yang Jul 07 '17 at 01:49
  • I could consider that, but I guess I am having an issue understanding something that "should" be simple. To keep it strongly typed, I would love to avoid making a case statement for every Object that I plan to Validate, my first example is `var result = db.Artists.Where(a => a.Name == name && a.Oid != oid).Count() == 0;`, then set it up for many more as I create new objects. – Derek Jul 07 '17 at 01:54
  • @Derek : Do you have `using System.Linq.Dynamic;`? – stomtech Jul 07 '17 at 04:17
  • 1
    Looks like .Dynamic got me a bit further, need to test to confirm. Needed to install package `Install-Package System.Linq.Dynamic`, then add `using System.Linq.Dynamic;` to the code. Thanks @stomtech – Derek Jul 07 '17 at 11:31

0 Answers0