Seuphoria
Seuphoria

Reputation: 17

Can not seed data with EF Code First

I found the problem, Solution is at comments.

I can create tables and diagram but I can not seed data to table.

1.I installed EF by Nuget.

2.From PM console I wrote Enable-Migrations –EnableAutomaticMigrations.

Model is in All.Model class library and and context methods are in All.Dal class library I did not understand what am I doing wrong can you help me?

This is my context code:

using All.Model;  

 namespace All.Dal  
 {
    public class AllDb : DbContext
    {
    public AllDb()
    {
        Database.Connection.ConnectionString = "Server=SEUPHORIA;Database=AllDb;UID=sa;PWD=123;";
    }

    public DbSet<Category> Categories { get; set; }
    public DbSet<Comment> Comments { get; set; }
    public DbSet<Line> Lines { get; set; }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<AllDb>(new DbStrategy());
        modelBuilder.Entity<Category>().Property(c => c.Name).IsRequired();
        modelBuilder.Entity<Comment>().Property(c => c.Letter).IsRequired();
    }
}

}

And this is my strategy code:

using All.Model;

namespace All.Dal
{
   public class DbStrategy : DropCreateDatabaseIfModelChanges<AllDb>
  {
      protected override void Seed(AllDb context)
    {
        List<Category> CategoryDefault = new List<Category> 
        {
            new Category { Name="Organic", UpID = 0 },
            new Category { Name="Object", UpID=0},
            new Category { Name="Time",UpID=0},
        };

        foreach (Category item in CategoryDefault)
        {
          context.Categories.Add(item);
        } context.Users.Add(new User { Name = "sss" });

    }
 }

}

this is my category class:

 public class Category : Standart
  {
    public int UpID { get; set; }
    public string Name { get; set; }
    public int LineID { get; set; }
    public virtual List<Line> Lines { get; set; }
 }

Upvotes: 1

Views: 773

Answers (1)

Brad C
Brad C

Reputation: 2982

You are adding the items into the DB context but are not committing the changes by calling SaveChanges() on them. Just add this one line:

protected override void Seed(AllDb context)
{
    List<Category> CategoryDefault = new List<Category> 
    {
        new Category { Name="Organic", UpID = 0 },
        new Category { Name="Object", UpID=0},
        new Category { Name="Time",UpID=0},
    };

    foreach (Category item in CategoryDefault)
    {
      context.Categories.Add(item);
    }
    context.Users.Add(new User { Name = "sss" });
    context.SaveChanges(); // make sure you save!
}

Upvotes: 1

Related Questions