c# - EF4 Code First 数据库生成

标签 c# asp.net-mvc database-design entity-framework-4

我是 Entity Framework 的初学者,我陷入了无法让代码生成数据库的困境。

我的上下文是这样的:

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

还有我的 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);
        }
    }

以及我在 Web.config 中的连接字符串:

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

谁能看出问题出在哪里吗?当我构建项目时,没有返回任何错误。 Global.axax 中的断点显示它命中了 Application_Start()。

最佳答案

您需要执行查询。这将检查数据库是否存在,如果不存在,则将创建数据库。

关于c# - EF4 Code First 数据库生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215192/

相关文章:

mysql - 未知列的结构数据库

c# - Moonlight、WebClient 和 "Exception has been thrown by the target of an invocation"

c# - 使用 AutoMapper 从实体映射到 DTO 或从 DTO 映射到实体时出错

c# - Url 验证属性将 `localhost` 标记为无效 Url

jquery - 在文本后显示所需的星号?

visual-studio - 用于SQLite的UWP数据库设计器

sql - 数据库架构规范化违规

c# - 为什么垃圾收集器只有 3 代,不多也不少?

c# - 安全地验证客户端到服务器

asp.net-mvc - 用户身份如何?应用程序生命周期中的主体集