2012-07-07 100 views
0

我在练习实体框架。我正在使用Razor Engine和EF Code First练习Asp.net MVC框架。在实践中,我发现问题很少。问题是实体框架不会在我的SQL中创建数据库。 我正在使用MSSQL 2008 VisualStudio 2011测试版本。我不知道问题是什么。 需要帮助。以下是我的代码:使用Razor Engine和EF CodeFirst创建MVC应用程序

Person.cs 

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Text; 

namespace MvcDemo.Data 
{ 
    public class Person 
    { 
     [Key] 
     public int PersonID { get; set; } 

     [Required] 
     [StringLength(40)] 
     public string FirstName { get; set; } 

     [Required] 
     [StringLength(30)] 
     public int LastName { get; set; } 

     public int? Age { get; set; } 

     [ForeignKey("PrefixID")] 
     public Prefix Prefix { get; set; } 


     [Required] 
     public int PrefixID { get; set; } 

    } 
} 

    Prefix.cs 

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Text; 

namespace MvcDemo.Data 
{ 
    public class Prefix 
    { 
     public int PrefixID { get; set; } 

     [Required] 
     [StringLength(20)] 
     public string PrefixName { get; set; } 
    } 
} 

MvcContext.cs 

using System; 
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Linq; 
using System.Text; 
using MvcDemo.Data; 


namespace MvcDemo.DataAccess 
{ 
    public class MvcContext : DbContext 
    { 
     public MvcContext() 
      : base("name = MvcDemoApp") 
     { 
     } 
     public DbSet<Person> People { get; set; } 

     public DbSet<MvcDemo.Data.Prefix> Prefix { get; set; } 

    } 
} 

ConnectionString: 
<connectionStrings> 
    <add name="MvcDemoApp" 
     connectionString="Server=.;Initial Catalog=MvcDemoApp;Integrated Security=true" 
    providerName="System.Data.SqlClient" /> 

回答

1

如果这是您的所有代码,则不会创建数据库并不奇怪。没有对数据库执行命令的代码。一旦你开始迭代例如MvcContext.People或做一些插入,你会注意到数据库被创建。

0

您应该使用包管理器控制台来执行此操作。

打开软件包管理器控制台窗口并运行“update-database”命令,该命令中仍然存在一个错误,因此您需要指定“startupprojectname”参数以在您的DbContext文件中执行它和连接字符串。

+0

好,我不能找到包管理器控制台:/在VS 2012 Beta版.. – 2012-07-08 11:52:30

+0

我找到了!哈哈抱歉 – 2012-07-08 11:57:46

+0

但我无法解决我的问题。问题依然存在! – 2012-07-08 18:50:51

相关问题