简体   繁体   中英

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));
            }
        }
    }
}

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM