Entity Framework database seed doesn't seed

I’m quite new to EF. I’m trying to override a Seed method inside my custom initializer, using MVC 4.

The problem is when EF creates the database, i don’t find any initial records inserted into my Admins table. Here’s my code :

namespace FP.Domain.Configurations
{
    public class InitializeSeed : DropCreateDatabaseIfModelChanges<EFDbContext>
    {
        protected override void Seed(EFDbContext context)
        {
            context.Admins.Add(new Admins
            {                
                Username = "admin",
                Password = "admin123456",
            });
            base.Seed(context);
        }
    }
}

And here’s my controller :

namespace FP.WebUI.Controllers
{
    public class AdminController : Controller
    {       
        public ViewResult Login()
        {
            Database.SetInitializer(new InitializeSeed());
            return View();
        }

    }
}

And here’s my Admins entity :

namespace FP.Domain.Entities
{
    public class Admins
    {
        public int ID { get; set; }
        public string Username { get; set; }
        public string HashedPassword { get; set; }

        private string _password;
        public string Password
        {
            set
            {
                this._password = value;
                byte[] tempSrc = ASCIIEncoding.ASCII.GetBytes(_password);                    
                HashedPassword = Convert.ToBase64String(new SHA256CryptoServiceProvider().ComputeHash(tempSrc));
            }
        }
    }
}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You are not saving your changes to the database. Note that the default implementation of Seed does nothing.

Try adding a call to SaveChanges in your Seed.

protected override void Seed(EFDbContext context)
{
    context.Admins.Add(new Admins
    {                
        Username = "admin",
        Password = "admin123456",
    });
    base.Seed(context);
    context.SaveChanges();
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply