janhartmann
janhartmann

Reputation: 15003

EF4 Code First database generation

I am a total beginner to Entity Framework and I am stuck where its not possible for me to make the code generate the database.

My context is like:

 public class ChatContext : DbContext
    {
        public ChatContext()
            : base("ChatContext")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ChatRoom>()
                         .Map(c => c.ToTable("chat_rooms"));

            modelBuilder.Entity<ChatUser>()
                        .HasMany(u => u.Rooms)
                        .WithMany(r => r.Users)
                        .Map(c => c.ToTable("chat_users"));

            modelBuilder.Entity<ChatUser>()
                       .HasMany(u => u.ConnectedUsers);

            base.OnModelCreating(modelBuilder);
        }

        public DbSet<ChatUser> Users { get; set; }
        public DbSet<ChatRoom> Rooms { get; set; }
        public DbSet<ChatMessage> Messages { get; set; }    
    }

And my Global.asax:

public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

        protected void Application_Start()
        {
            Database.SetInitializer<ChatContext>(new DropCreateDatabaseIfModelChanges<ChatContext>());

            RegisterRoutes(RouteTable.Routes);
        }
    }

And my connection string in Web.config:

<connectionStrings>
    <add name="ChatContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ChatContext;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

Can anyone spot where the problem lies? When I build the project, no errors are returned. A break point in Global.axax shows it hits the Application_Start().

Upvotes: 2

Views: 1012

Answers (1)

Xharze
Xharze

Reputation: 2733

You need to perform a query. This will check if the database exists, if it doesn't then it will be created.

Upvotes: 2

Related Questions