0

I am trying to create a small test site in mvc. I've created the model as :

  public class Subject_Master
    {
        public Subject_Master()
        {
        }
        public Subject_Master(string Subject_Name)
        {
            this.Subject_Name = Subject_Name;
        }
        public int Subject_MasterId { get; set; }
        public string Subject_Name { get; set; }
    }

Context is :

public class MyContext : DbContext
    {
        public DbSet<StudentAccount> StudentAccount { get; set; }
        public DbSet<Subject_Master> Subject_Master { get; set; }
    }

The initializer :

namespace MyProj.Models
{
    public class DBInitializer:DropCreateDatabaseIfModelChanges<XpertsContext>
    {
        protected override void Seed(XpertsContext context)
        {
            var Subject_Master_List = new List<Subject_Master>();

            Subject_Master_List.Add(new Subject_Master("English"));
            Subject_Master_List.Add(new Subject_Master("Hindi"));
            Subject_Master_List.Add(new Subject_Master("Bengali"));

            foreach (var subject in Subject_Master_List)
            {
                context.Subject_Master.Add(subject);
            }

            context.SaveChanges();
        }
    }
}

The database is created but the data is not getting inserted.

What am I doing wrong ?

1 Answer 1

2

You seem to have forgotten to use this DBInitializer class that you wrote. In your Application_Start you could specify the desired initializer using the SetInitializer static method:

Database.SetInitializer(new DBInitializer());

Also don't forget that the initializer's Seed method will be called the first time a query is made against MyContext, not when your application starts.

Alternatively you could specify the initializer in your web.config file as shown here.

Sign up to request clarification or add additional context in comments.

2 Comments

I did that. But now when I ran the project, it didn't insert the data. How ever when I deleted the entire db, and re-ran the project. it got inserted. Is there any way, where, if the db is created already, the data will be inserted without having to delete/re-create db ?
That's normal, look what class you have derived from: DropCreateDatabaseIfModelChanges. The IfModelChanges part is important. You probably need DropCreateDatabaseAlways if you want your database to be always recreated when the context is first used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.