89
loading...
This website collects cookies to deliver better user experience
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; }
}
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'. 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);
}
_dbContext.Add(livingThing);
_dbContext.SaveChanges();
var linqQuery = _dbContext.GetType().GetProperty("Animals").GetValue(_dbContext) as IQueryable<LivingThing>;
var entity = linqQurey.Where(x => x.Id == 1).First();
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();
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();