-1

This code is used to pass table (Entity) name to a method in a controller:

public JsonResult IsSubCategoryExist(string Name, int? ID, string ClassName)
{
        //my code..
}

ClassName is the name of the table I need to retrieve from my database. My context definition:

ApplicationDbContext db = new ApplicationDbContext();

Can someone please help me do it? Thanks in advance.

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
R K
  • 133
  • 12
  • 3
    Possible duplicate of [dynamic table name in Entity](https://stackoverflow.com/questions/46575714/dynamic-table-name-in-entity) and [Dynamic table names in Entity Framework linq](https://stackoverflow.com/questions/31033055) – adiga Feb 07 '19 at 07:50
  • @adiga - Thanks for the reference. In your reference, Type is known and is translated using `typeof` keyword. While in my case, Type is not known. It depends on the `ClassName` . If I use that methodology and suppose I have 1000 different `ClassName` strings in my code, I'll have to hardcode all those 1000 `ClassName` to translate them to tables. Very something that I'm looking to avoid here. – R K Feb 07 '19 at 08:02
  • @RK Have you tried my answer please? – TanvirArjel Feb 07 '19 at 10:58
  • @TanvirArjel Yes. I'm stuck with `ClassName` now. I'm passing it from my `Model` class as a parameter on `Remote` attribute with a string value but it is coming as `undefined`. I've shown its implementation here: https://stackoverflow.com/questions/54551577/send-parameter-on-remote-attribute-in-mvc – R K Feb 07 '19 at 11:12

2 Answers2

1

You can do as follows:

public async Task<JsonResult> IsSubCategoryExist(string Name, int? ID, string ClassName)
{
      var type = Assembly.GetExecutingAssembly()
                .GetTypes()
                .FirstOrDefault(t => t.Name == ClassName);

      if (type != null)
      {
         DbSet dbSet = _dbContext.Set(type);

         List<object> subCategories;
         if(ID == null)
         {
             subCategories = await dbSet.Where("Name == @0", Name) 
                                        .Take(1).ToListAsync();
         }
         else
         {
             subCategories = await dbSet.Where("Name == @0 and Id != @1", Name,ID)
                                        .Take(1).ToListAsync();
         }

         if(subCategories.Count > 0)
         {
            return Json(false,JsonRequestBehavior.AllowGet);
         }
         return Json(true,JsonRequestBehavior.AllowGet);
     }
     else
     {
        throw new Exception("Table name does not exist with the provided name");
     }
}

Note: Don't forget to install System.Linq.Dynamic from Nuget

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
  • 1
    Throwing error on line: `await dbSet.Where("Name == @0 and ID == @1", Name, ID).ToListAsync();` in the browser stating: `Operator '==' incompatible with operand types 'Int32' and 'Object'` – R K Feb 07 '19 at 12:06
  • 1
    Done. Thank you. – R K Feb 07 '19 at 12:46
0

The answer of Viktor Bahtev to the duplicate question seems to work like a charm. I repeat his solution here to show how to get the assembly to search for the entity type, if the entities are defined in another assembly that is not the executing assembly.

This assumes that all your entity classes are in the same known assembly.

DbContext db;
var assemblyName = "MyProject.MyEntities";
var entityName = "FooEntity";
long theEntityId = 1337;

var assembly = AppDomain.CurrentDomain.GetAssemblies()
                   .SingleOrDefault(a => a.GetName().Name == assemblyName);

var entityType = assembly.GetTypes()
                   .FirstOrDefault(t => t.Name == entityName);

var dbSet = db.Set(entityType);

var singleEntry = dbSet.Find(theEntityId);
var allEntries = dbSet.ToArray();
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36