简体   繁体   English

从Entity Framework连接字符串创建DataContext?

[英]Create DataContext from Entity Framework connection string?

I'm trying to make this call in my code: 我正在尝试在我的代码中进行此调用:

string conn = ConfigurationManager.ConnectionStrings["MyDBEntities"].ConnectionString;
DataContext context = new DataContext(conn);
Table<MyApp.Entities.Employee> myTable = context.GetTable<MyApp.Entities.Employee>();

Here's my connection strings: 这是我的连接字符串:

<connectionStrings>
  <add name="MyDBEntities" connectionString="metadata=res://*/Entities.MyDB.csdl|res://*/Entities.MyDB.ssdl|res://*/Entities.MyDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=STEVEN-PC;Initial Catalog=MyDB;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
  <add name="MyDB" connectionString="Server=STEVEN-PC;Database=MyDB;Trusted_Connection=yes;" />
</connectionStrings>

I get an error when creating the DataContext: Keyword not supported: 'metadata'. 创建DataContext时出错: 不支持关键字:'metadata'。

If I use the second connection string, I get an error when trying to get the table: Server Error in '/' Application. 如果我使用第二个连接字符串,我在尝试获取表时出错'/'应用程序中的服务器错误。 The type 'MyApp.Entities.Employee' is not mapped as a Table. “MyApp.Entities.Employee”类型未映射为表格。

What am I doing wrong here? 我在这做错了什么?

You are mixing and matching LINQ-to-SQL and LINQ-to-Entites ; 您正在混合和匹配LINQ-to-SQLLINQ-to-Entites ; the two are not compatible. 两者不兼容。

When you create entity models with LINQ-to-Entities, it creates an object derived from ObjectContext which would have the IQueryable<T> implementations that you would use for the base of your query. 当您使用LINQ-to-Entities创建实体模型时,它会创建一个派生自ObjectContext的对象,该对象将具有您将用于查询基础的IQueryable<T>实现。 This ObjectContext also will have constructors that take the appropriate metadata to map the entity models to the database; ObjectContext还将具有构造函数,这些构造函数采用适当的元数据将实体模型映射到数据库; this is why Entity Framework connection strings require Metadata references. 这就是Entity Framework连接字符串需要Metadata引用的原因。

When you try and use LINQ-to-SQL, you can pass it a regular database connection to the DataContext class (or a derived class). 当您尝试使用LINQ-to-SQL时,可以将常规数据库连接传递给DataContext类(或派生类)。 The DataContext handles the mapping of your objects to the database differently than the Entity Framework; DataContext以不同于Entity Framework的方式处理对象到数据库的映射; it relies on attributes on the models to map to tables/columns (using the TableAttribute and ColumnAttribute attributes respectively). 它依赖于模型上的属性来映射到表/列(分别使用TableAttributeColumnAttribute属性)。 These attributes are not present when you created entities using the Entity Framework. 使用实体框架创建实体时,这些属性不存在。

Note: You can use XML mapping files (a different sort than what is used in the Entity Framework) with LINQ-to-SQL, but it's not commonly used. 注意:您可以使用XML映射文件(与实体框架中使用的不同的类型)与LINQ-to-SQL,但它并不常用。

That said, the easiest approach would be to choose one technology stack (LINQ-to-SQL or LINQ-to-Entities) and stick with that. 也就是说,最简单的方法是选择一个技术堆栈(LINQ-to-SQL或LINQ-to-Entities)并坚持下去。

Just in case, this is what I did. 以防万一,这就是我所做的。 I don't have connections in the Web.config since I need a DropDownList to select the connection. 我在Web.config中没有连接,因为我需要一个DropDownList来选择连接。

string connDev = @"metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=""Server=MyDevServer;Database=MyDB;Integrated Security=True""";

EntityConnection ec = new EntityConnection(connDev);

MyDBContext db = new MyDBContext(ec);

var people = db.People.ToList();

If you want to use Entity Framework you should use ObjectContext, not DataContext as this is a base class from Linq-To-Sql. 如果你想使用Entity Framework,你应该使用ObjectContext,而不是DataContext,因为这是Linq-To-Sql的基类。

When you create ADO.NET Entity Data Model , Visual Studio generates (after you complete a generate model from database wizard or use the designer), a class that is derived from ObjectContext that has a default connection string (that you choose at the wizard). 当您创建ADO.NET实体数据模型时,Visual Studio生成(在您从数据库向导完成生成模型或使用设计器之后),从ObjectContext派生的类,该类具有默认连接字符串(您在向导中选择) 。 Here you can see a nice tutorial from ADO.NET team how to start using the EF. 在这里,您可以看到ADO.NET团队的一个很好的教程如何开始使用EF。

You are not supposed to use ObjectContext directly, at least not without manually creating the metadata files and pointing to them in your connection string (Never seen DataContext class being used directly, so if I'm wrong someone correct me) , as the wizard I mentioned above creates all sorts of mapping data - to map SQL tables/views/other stuff to Entity classes. 你不应该直接使用ObjectContext,至少不是没有手动创建元数据文件并在你的连接字符串中指向它们(从未见过直接使用的DataContext类,所以如果我错了有人纠正我),作为向导我上面提到的创建各种映射数据 - 将SQL表/视图/其他东西映射到实体类。

if you want to supply your own connection to the class you can do it programmatically with EntityConnectionStringBuilder . 如果要提供自己的类连接,可以使用EntityConnectionStringBuilder以编程方式进行。

This is an example how to use EntityConnectionStringBuilder it from MSDN 是一个如何从MSDN使用EntityConnectionStringBuilder的示例

Edit : I mistakenly wrote about DataContext as if it was EF base class for designer generated code. 编辑:我错误地写了关于DataContext,好像它是设计器生成的代码的EF基类。 It is as casperOne stated a base class for Linq-To-Sql classes. 就像casperOne为Linq-To-Sql类声明了一个基类。

Changed my answer to reflect his comment 改变了我的回答以反映他的评论

The connectionstring is already defined in the EntityModel, so you can try to use the default connection as follows: connectionstring已在EntityModel中定义,因此您可以尝试使用默认连接,如下所示:

using (context = new DataContext())
{
    var myTable = context.GetTable<MyApp.Entities.Employee>();
}

You can also try the following: 您还可以尝试以下方法:

MyApp.Entities.Employee myTable = context.GetTable<MyApp.Entities.Employee>();

EDIT: GetTable<T>() will return type T, so the syntax above will be correct. 编辑: GetTable <T>()将返回类型T,因此上面的语法是正确的。

If you want to override the connection string, use the second connection string from your web.config file (MyDB) 如果要覆盖连接字符串,请使用web.config文件(MyDB)中的第二个连接字符串

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

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