简体   繁体   English

C#中带有dll文件的实体框架

[英]Entity Framework with dll files in C#

I am new to entity framework. 我是实体框架的新手。 I am creating a module that have to interact with database. 我正在创建一个必须与数据库交互的模块。 The module will be general so it can be referenced in different projects. 该模块将是通用模块,因此可以在不同项目中引用。 As those projects will have different databases so the confusion is that how I will get reference to that database in my library as it is going to be different each time? 由于这些项目将具有不同的数据库,所以困惑在于我如何在我的库中引用该数据库,因为每次数据库都会有所不同?

For explaining purpose, if I shall be using sqlConnection then it will like 为了说明目的,如果我将使用sqlConnection,它将

class myClass
{
   SqlConnection con;
   public myClass(SqlConnection con)
   {
       this.con=con;
   }

   public DataTable DoSomething()
   {
       try
       {
           connection.open();
           using (SqlDataAdapter com= new SqlDataAdapter("Select * from table1",con))
           {
               DataTable temp = new DataTable();
               com.SelectCommand.ExecuteNonQuery();
               com.Fill(temp);
               return temp;
           }
        }
        catch (Exception ex) {}
    }
}

如果使用EF,则数据库结构(数据上下文)应该(在共享项目之间)相同(除非为每个项目定义单独的数据上下文),否则连接字符串可以保存在配置文件中(对于每个单独的项目)。

You can implement EF Code First in a Class Library Project. 您可以在类库项目中首先实现EF代码 Each other project that uses the model will have a reference to that project. 使用该模型的每个其他项目都将对该项目进行引用。 Since each project will have its own database then each project has to have its own connection string, you can place this in the app.config file. 由于每个项目都有其自己的数据库,因此每个项目都必须具有自己的连接字符串,因此可以将其放在app.config文件中。 Entity framework will add something like the following to your app.config in your class library project: 实体框架将在类库项目的app.config中添加以下内容:

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="Your Connection string" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>

The only thing you have to do or at least what I did and worked for me is to add entity to your other projects and change your connection string for each one of those. 您唯一需要做的事情,或者至少是我为我做过的工作,就是将实体添加到其他项目中,并为每个项目更改连接字符串。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM