无法在多项目解决方案中配置EF6的连接字符串

时间:2014-07-30 09:30:46

标签: entity-framework sql-server-ce-4 entity-framework-6.1

我有两个项目的解决方案:

enter image description here

我通过nuget为它们添加了Entity Framework 6和Sql server compact。

<packages>
  <package id="EntityFramework" version="6.1.1" targetFramework="net45" />
  <package id="EntityFramework.SqlServerCompact" version="6.1.1" targetFramework="net45" />
  <package id="Microsoft.SqlServer.Compact" version="4.0.8876.1" targetFramework="net45" />
</packages>

我将此连接字符串添加到DAL的Web配置:

 <connectionStrings>
    <remove name="connectionString"/>
    <add name="connectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

实体框架配置(我只将contexts添加到BreezeDemo.DAL):

<entityFramework>
    <contexts>
      <context type="BreezeDemo.DAL.MyDbContext, BreezeDemo.DAL">
        <databaseInitializer type="BreezeDemo.DAL.SchoolInitializer, BreezeDemo.DAL" />
      </context>
    </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="System.Data.SqlServerCe.4.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
    </providers>
  </entityFramework>

这里是我在上下文中的代码:

public class MyDbContext : DbContext
    {
        public MyDbContext()
            : base("connectionString")
        {
            Database.SetInitializer<MyDbContext>(new SchoolInitializer());
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }

当我尝试学生名单时:

public class StudentRepository
    {
        MyDbContext dal = new MyDbContext();

        public List<Student> GetAll()
        {
            return dal.Students.ToList();
        }
    }

EF代码首次运行,但它在web配置中不使用我的连接字符串。它创建db文件名&#34; connectionString&#34;在BreezeDemo\App_Data。我在web配置中的连接想要创建db文件名:&#34; Database&#34;在BreezeDemo.DAL\App_Data

我错过了什么吗?请帮我把它搞定。

1 个答案:

答案 0 :(得分:2)

如果我没记错,您的启动项目为BreezeDemo,但您的连接字符串位于BreezeDemo.DAL

您需要从{{1}复制 <configSections> <connectionStrings> <entityFramework> 元素转到Web.Config of BreezeDemo.DAL