我是 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()。