Click here to Skip to main content
Click here to Skip to main content

Custom Seed Serializer for Entity Framework Code First C#

, 11 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DiponRoy

Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
QuestionWhat is seeding you mean here? PinmemberTridip Bhattacharjee11-Jun-14 21:23 
AnswerRe: What is seeding you mean here? Pinmemberjohannesnestler11-Jun-14 23:20 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 11 Jun 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid