2014-09-01 74 views
0

我试图先用代码来生成一个数据库和每一个我的应用程序运行的时候种子它,但是我得到以下错误:代码优先数据库生成外部DLL

Cannot attach the file 'C:{filepath}\Application\App_Data\mydatabase.mdf' as database 'mydatabase'.

我试着做'更新数据库'(根据其他问题推荐),但不生成.mdf文件。

这是用来连接字符串:

Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\mydatabase.mdf;Initial Catalog=mydatabase;Integrated Security=True

由于一些背景资料,我有坐不同的解决方案两个不同的项目:

  • 应用

The “应用”项目已在“域”项目

在域项目的引用我已经创建了我的第一个代码模型和的DbContext:

public class ApplicationContext : IdentityDbContext<User, IntRole, int, IntUserLogin, IntUserRole, IntUserClaim> 
{ 
    public ApplicationContext() 
     : base(nameOrConnectionString: "constr") { } 

    public ApplicationContext(string connectionString) 
     : base(nameOrConnectionString: connectionString) { } 

    static ApplicationContext() 
    { 
     Database.SetInitializer<ApplicationContext>(null); 
    } 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     // Use singular table names 
     base.OnModelCreating(modelBuilder); 

     modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 

     modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); 

     Configuration.ProxyCreationEnabled = false; 
     Configuration.LazyLoadingEnabled = false; 
     Configuration.ValidateOnSaveEnabled = false; 
    } 

    public DbSet<Item> Items { get; set; } 
} 

public class ApplicationContextInitializer : DropCreateDatabaseAlways<ApplicationContext> 
{ 
    protected override void Seed(ApplicationContext context) 
    { 

     new List<Item> 
     { 
      new Item("test") 
      { 
      }, 
      new Item("test2") 
      { 
      }, 
      new Item("test3") 
      { 
      } 
     }.ForEach(t => context.Items.Add(t)); 

     base.Seed(context); 
    } 
} 

里面在Global.asax我有我的应用程序项目以下:

  Database.SetInitializer(new ApplicationContextInitializer()); 

我然后尝试将数据添加到数据库中:

 mUnitOfWork = new UnitOfWork(new RepositoryProvider(new RepositoryFactories())); 

     mUnitOfWork.ItemRepository.Add(new Item("my item")); 
     mUnitOfWork.Save(); 

回答

0

原来你需要一个上下文到web.config中如下:

<configuration> 
    <entityFramework> 
    <contexts> 
     <context type="Application.Data.ApplicationContext, Application.Data"> 
     <databaseInitializer type="Application.Data.ApplicationContextInitializer, Application.Data" /> 
     </context> 
    </contexts> 
    </entityFramework> 
</configuration> 

有用的链接,如果其他人有类似的问题:http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

0

延长正确的答案,你也可以添加此代码:

public class DBConfig 
{ 
    public static readonly DBInitializer Initalizer = new DBInitializer(); 

    public static void InitalizeDB() 
    { 
     System.Data.Entity.Database.SetInitializer<DMPDataContext>(Initalizer); 
    } 
} 
protected void Application_Start() 
    { 
     //common application startups 
     DBConfig.InitalizeDB(); 
     //...   
    } 
相关问题