Click here to Skip to main content
15,881,898 members
Articles / DevOps / Load Testing
Tip/Trick

Custom Seed Serializer for Entity Framework Code First C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
11 Jun 2014CPOL1 min read 16.1K   99   9   2
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

C#
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

C#
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:

C#
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhat is seeding you mean here? Pin
Tridip Bhattacharjee11-Jun-14 21:23
professionalTridip Bhattacharjee11-Jun-14 21:23 
AnswerRe: What is seeding you mean here? Pin
johannesnestler11-Jun-14 23:20
johannesnestler11-Jun-14 23:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.