How to CRUD dynamically in Entity Framework

This topic is mainly focused on performing CRUD operations using entity framework at runtime. That is, we can choose to which Table/DbSet we can CRUD data.

Prerequisite

Lets create a DbContext MyDbContext with 2 DbSets Animals and Birds.

public class MyDbContext : DbContext
{
    public DbSet<Animal> Animals { get; set; }
    public DbSet<Bird> Birds { get; set; }
}

public class Animal : LivingThing
{
    public int NumberOfTeeths { get; set; }
    public int RunningSpeed { get; set; }
}

public class Bird : LivingThing
{
    public int MaxFlyingDistance { get; set; }
    public int IsHerbivorous { get; set; }
}

public class LivingThing
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Create

  • To create an instance of a Animal or Bird entity. First get access to the DbSet<> by its name. Then take the first Type from its generic arguments.
var entityType = _dbContext.GetType().GetProperty("Animals").PropertyType.GetGenericArguments().FirstOrDefault();
object livingThing = Activator.CreateInstance(entityType) as LivingThing;
  • Activator can be used to create an instance of a given 'Type'.
  • Now you can set commonly available properties such as Id and Name directly and properties which are specific to an entity can set using reflection.
livingThing.Id = 1;
livingThing.Name = "Tiger";

// Set other properties dynamically
Dictionary<string, int> otherProperties = new Dictionary<string, int>()
{
    { "NumberOfTeeths", 10 },
    { "RunningSpeed", 50 },
}

// This will set all the properties which are specific to a class.
foreach(var prop in otherProperties.Keys)
{   
    string propertyValue = otherProperties[prop];
    livingThing.GetType().GetProperty(prop).SetValue(livingThing, propertyValue);
}
  • Add the entity
_dbContext.Add(livingThing);
_dbContext.SaveChanges();

Read

  • Get the IQueryable<> property through reflection
var linqQuery = _dbContext.GetType().GetProperty("Animals").GetValue(_dbContext) as IQueryable<LivingThing>;
var entity = linqQurey.Where(x => x.Id == 1).First();

Update

  • Get the entity by Id, update properties and call SaveChanges() to update the entity.
var linqQuery = _dbContext.GetType().GetProperty("Animals").GetValue(_dbContext) as IQueryable<LivingThing>;
var entity = linqQurey.AsTracking().Where(x => x.Id == 1).First();
entity.Name = "New Name";
...
...
_dbContext.SaveChanges();

Delete

  • Get the entity by Id. Use Remove() to delete the entity.
var linqQuery = _dbContext.GetType().GetProperty("Animals").GetValue(_dbContext) as IQueryable<LivingThing>;
var entity = linqQurey.AsTracking().Where(x => x.Id == 1).First();
_dbContext.Remove(entity);
_dbContext.SaveChanges();

Thanks for reading...

73