Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Custom Seed Serializer for Entity Framework Code First C#

0.00/5 (No votes)
11 Jun 2014 1  
Custom Seed Serializer for Entity Framework Code First C#

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:

  1. EntitySeedSerializer - holds the seeds for particular entity
  2. 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>
{
    /*Customer seed serializer*/
    private readonly DbSeedSerializer _dbSeedSerializer;

    public UmsContextInitializer()
    {
        _dbSeedSerializer = new DbSeedSerializer();
    }

    protected override void Seed(UmsContext context)
    {
        /*Adding seed*/
        _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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here