从主项目中的子项目共享EF连接字符串

时间:2013-10-31 09:37:51

标签: entity-framework ef-code-first

我有两个项目

MyProject //MVC 3 app
MyProject.DAL //Class Library project type

MyProject.DAL内,有一个文件夹EntityModels,其中包含生成的实体(EF Code-First方法):

namespace MyProject.DAL.EntityModels
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class myEntities : DbContext
    {
        public myEntities() : base("name=myEntities")
        {
             ...
        }
    }
}

的app.config:

 <add name="myEntities" connectionString="metadata=res://*/EntityModels.DBMainModel.csdl|res://*/EntityModels.DBMainModel.ssdl|res://*/EntityModels.DBMainModel.msl;provider=..." providerName="System.Data.EntityClient" />

然后,我想在我的MyProject项目中使用该实体,因此我在web.config文件中添加了相同的连接字符串。

但是,我收到Unable to load the specified metadata resource.错误。我尝试在web.config中进行一些修改

<add name="myEntities"
connectionString="metadata=res://*/MyProject.DAL.EntityModels.DBMainModel.csdl|
                           res://*/MyProject.DAL.EntityModels.DBMainModel.ssdl|
                           res://*/MyProject.DAL.EntityModels.DBMainModel.msl;provider=..." providerName="System.Data.EntityClient" />

<add name="myEntities"
connectionString="metadata=res://MyProject.DAL.EntityModels.DBMainModel.csdl|
                           res://MyProject.DAL.EntityModels.DBMainModel.ssdl|
                           res://MyProject.DAL.EntityModels.DBMainModel.msl;provider=..." providerName="System.Data.EntityClient" />


<add name="myEntities"
connectionString="metadata=res://MyProject.DAL/EntityModels.DBMainModel.csdl|
                           res://MyProject.DAL/EntityModels.DBMainModel.ssdl|
                           res://MyProject.DAL/EntityModels.DBMainModel.msl;provider=..." providerName="System.Data.EntityClient" />

但没有任何作用。如何解决?

1 个答案:

答案 0 :(得分:0)

如果它是代码优先的,您应该将pure connectionString值放在相应的.config文件中(您正在处理SqlClient而不是EntityClient)。
要了解有关ConnectionString值的更多信息,请查看http://www.connectionstrings.com/sql-server/

对于SQL Server数据库,基本上如下所示:

<add name="MyEntities" connectionString="Data Source=myServerName\myInstanceName;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;" providerName="System.Data.SqlClient"/>