首页 > 解决方案 > 使用实体框架创建数据访问项目

问题描述

我有自动化测试解决方案,它(可以说)包含 3 个项目:

  1. DataAccessProject(从 db 获取数据,因此可以称为生产者,它是我的 StartUpFile)
  2. 页面对象存储
  3. 方案和步骤项目 我要做的是让 1. 项目使用 EF,而不通知任何其他项目 EF 甚至存在于解决方案中。我希望(例如)我的第三个项目能够调用诸如 DataAccessProject.SomeMethod.GiveMeSomeUsers() 之类的东西,因此 DataAccessProject 将从实体中获取记录,执行魔术并简单地返回信息以与页面对象中的值进行比较。

我正在努力解决的是:首先我遇到了这个错误:

No connection string named 'MyEntities' could be found in the application config file

我已经阅读了一些关于堆栈的文章并添加了连接字符串节点(我想避免它),现在我收到了这个错误:

Errors: TestModel.ssdl(2,2) : error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file.

所以,我的问题是,我做错了什么?我如何安装 EF 而无需在每个项目中添加对 EF 的引用(我相信这是 EF 现在想要的)。

相关 .config 节点:

<entityFramework>
  <defaultConnectionFactory         type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,     EntityFramework">
    <parameters>
      <parameter value="mssqllocaldb" />
    </parameters>
  </defaultConnectionFactory>
  <providers>
    <provider invariantName="System.Data.SqlClient"     type="System.Data.Entity.SqlServer.SqlProviderServices,     EntityFramework.SqlServer" />
  </providers>
</entityFramework>
<connectionStrings>
  <add name="test1Entities"     connectionString="metadata=res://*/TestModel.csdl|res://*/TestModel.ssdl|res://*/TestModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MSSQL-TEST;initial catalog=testCATALOG;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"         <providerName="System.Data.EntityClient" />
</connectionStrings>

现在我从我的 3 项目中调用这个方法

public static void TestMyEF()
{
    using (var ctx = new test1Entities())
    {
        var abc = ctx.someTable.FirstOrDefault();
    }
}

上下文 ctor:

public test1Entities()
: base("name=test1Entities")
{
}

Ps 我使用的是 DB 优先方法(从现有 DB 创建 .edxm),我有点担心,因为我的 .config 节点包含<parameter value="mssqllocaldb" />,DB 不是本地的。

标签: c#entity-framework

解决方案


为结果创建一个通用类库,例如:

public class MyResultClass
{
    public readonly object Value;
    public readonly Exception ResultException;
    //add more properties if needed

    public MyResultClass(object value)
    {
        this.ResultException = null;
        this.Value = value;
    }

    public MyResultClass(Exception ex)
    {
        this.ResultException = ex;
    }
}

然后在你的项目中使用这个类的引用,这样你就没有依赖,entity-framework然后你可以使用 json(序列化和反序列化)来将数据从你的DAP(DataAccessProject)到客户端(调用项目)转换。


推荐阅读