Introduction
During production time, database with seed data is always a best particle to start with. This seed data could also be used for logic and load testing.
But as the number of database entities increases, so does the seed data. Sometimes, managing the seeds could become a burden within a single seed method.
Background
Entity framework code first provides a lot of managed utility classes like the Fluent API configuration classes. But for seed serialization, they haven't done anything yet.
As the number of entities increases, the seed data management becomes a problem to manage them all. So here, we will try to build some utility class to make seed data more manageable.
To create the seeds serializer, we will need two utility classes:
EntitySeedSerializer
- holds the seeds for particular entity
DbSeedSerializer
- triggers the EntitySeedSerializer
to start seeding
EntitySeedSerializer
public class EntitySeedSerializer<TEntity> where TEntity : class
{
public List<TEntity> Entities { get; private set; }
public EntitySeedSerializer()
{
Entities = new List<TEntity>();
}
protected bool Seed(TEntity entity)
{
Entities.Add(entity);
return true;
}
protected bool Seed(List<TEntity> entities)
{
foreach (var entity in entities)
{
Seed(entity);
}
return true;
}
public void SerializeInto(DbContext context)
{
try
{
foreach (var aEntity in Entities)
{
context.Set<TEntity>().Add(aEntity);
context.SaveChanges();
}
}
catch (Exception exception)
{
string msg = String.Format("Error to serialize {0} seeds.", typeof (TEntity).Name);
throw new Exception(msg, exception);
}
}
}
DbSeedSerializer
internal class DbSeedSerializer
{
public void Selialize<TEntity>(DbContext context, EntitySeedSerializer<TEntity> entitySeedSerializer) where TEntity : class
{
entitySeedSerializer.SerializeInto(context);
}
}
Using the Code
In the contextInitializer
class for our dbContext
, we will place the newly created Seed Serializer and seeds like:
class UmsContextInitializer : DropCreateDatabaseAlways<UmsContext>
{
private readonly DbSeedSerializer _dbSeedSerializer;
public UmsContextInitializer()
{
_dbSeedSerializer = new DbSeedSerializer();
}
protected override void Seed(UmsContext context)
{
_dbSeedSerializer.Selialize(context, new DepartmentSeed());
_dbSeedSerializer.Selialize(context, new StudentSeed());
}
}
Now let’s create seeds for a particular DbContext
Entity, like here we are creating seeds for Department
entity:
class DepartmentSeed : EntitySeedSerializer<Department>
{
public DepartmentSeed()
{
var list = new List<Department>()
{
new Department(){ Name = "Math"},
new Department(){ Name = "Physics"},
new Department(){ Name = "English"},
};
var aDepartment = new Department() {Name = "Economics"};
Seed(list);
Seed(aDepartment);
}
}
Find the VS 2010 solution in the attachment. Rebuild it, let entity framework be installed using nuget.