EF 6 seed not working

kobosh 176 Reputation points
2021-08-19T09:30:39.473+00:00

I am following through with EF6 tutorial

I followed the steps copied code from website into visual studio 2013. First problem the database was not created; I found solution by adding this to Global Application_Start method

 ProductContext context = new ProductContext();  
            context.Database.Initialize(true);  

Database was created but without seeding.
Please help

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,395 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,271 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Yijing Sun-MSFT 7,066 Reputation points
    2021-09-02T08:55:27.537+00:00

    Hi @kobosh ,
    I think there are two ways to call the seed() method.First,you could call Update-Database from the Package Manager Console.
    You could refer to below article:
    https://learn.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-3
    Second,you could call the seed method by yourself. You could change your InitializeDatabase method. Just like this:
    DatabaseContext class:

    public DatabaseContext() : base("DatabaseContext")  
     {  
        InitializeDatabase();  
     }  
      
     public DatabaseContext(string connectionString) : base(connectionString)  
     {  
         Database.Connection.ConnectionString = connectionString;  
         InitializeDatabase();  
     }  
      
     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
     {  
         modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  
     }  
    

    changed my InitializeDatabase method from:

    private void InitializeDatabase()  
    {  
        Database.SetInitializer(new DatabaseInitializer());  
        if (!Database.Exists())  
        {  
            Database.Initialize(true);  
        }              
    }  
    

    to:

    protected virtual void InitializeDatabase()  
    {  
        if (!Database.Exists())  
        {  
            Database.Initialize(true);  
            new DatabaseInitializer().Seed(this);  
        }              
    }  
    

    More details,you could refer to below article:
    https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.database.initialize?redirectedfrom=MSDN&view=entity-framework-6.2.0#overloads

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments