Skip to content Skip to sidebar Skip to footer

Dynamic Table Name With Entity Framework

I have many tables with the same model structure but with other table names with other data (in this case will be ~100 tables). I want to dynamically switch table name in runtime u

Solution 1:

Do you want to do like this?

foreach (string tableName innew[] { "Table1", "Table2" })
{
   var result = dbContext.Database.SqlQuery<SpecificModel>(string.Format("SELECT * FROM {0} WHERE ID=@p0", tableName), 1).FirstOrDefault();
}

Solution 2:

I did something like this. http://nodogmablog.bryanhogan.net/2013/08/entity-framework-in-an-dynamics-nav-navision-envirnoment/

I had tables which were identical, but they had different names. For example, a customer table but with different prefixes for different companies.

[ACME$Customer] 
[SuperCorp$Customer]

I ended up using dynamic compilation. It's a pretty detailed blog post so I won't go into it here.

Solution 3:

You can do this:

// Gets entity type from specified namespace/assemblyTypeentityType= Type.GetType(string.Format("Your.NameSpace.{0},{1}", entityName, "Assembly.Name"));
        // Finds item to update based on its primary key valuevarentity= _dbContext.Find(entityType, entityKey);
        // Finds column to update preference forPropertyInfopropertyInfo= entity.GetType().GetProperty(entityField);
        // Set and update (date example given)
        propertyInfo.SetValue(entity, isOptIn ? (DateTime?)null : (DateTimeOffset?)DateTime.Now, null);
        _dbContext.SaveChanges();

Post a Comment for "Dynamic Table Name With Entity Framework"