我是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()。
答案 0 :(得分:2)
您需要执行查询。这将检查数据库是否存在,如果不存在则会创建。