简体   繁体   English

向下转换ObjectContext到实体集合

[英]Downcast ObjectContext to Entities collection

I have an entity model created with a database-first approach in EF4.0. 我在EF4.0中使用数据库优先方法创建了一个实体模型。

I want to be able to use my model without an app.config file because my connection settings are stored in a separate configuration medium. 我希望能够在没有app.config文件的情况下使用我的模型,因为我的连接设置存储在单独的配置介质中。 This forces me to work directly with the ObjectContext class, passing in a valid EF connection string. 这迫使我直接使用ObjectContext类,传入有效的EF连接字符串。 Here is how I instantiate an ObjectContext: 这是我实例化ObjectContext的方法:

var ctx = new ObjectContext(entityConnectionString);

This executes correctly, and I can succesfully run SQL commands against the db using ctx.ExecuteStoreCommand(). 这可以正确执行,并且我可以使用ctx.ExecuteStoreCommand()对数据库成功运行SQL命令。

The name of my generated model is MyEntities. 我生成的模型的名称是MyEntities。 This is derived from ObjectContext, as can be seen in MyEntities.Designer.cs: 这是从ObjectContext派生的,如MyEntities.Designer.cs中所示:

public partial class MyEntities : ObjectContext

However, if I try to cast ctx to MyEntities object: 但是,如果我尝试将ctx强制转换为MyEntities对象:

MyEntities myEntities = (MyEntities)ctx;

I get an error saying 我说错了

Cannot cast 'ctx' (which has an actual type of 'System.Data.Objects.ObjectContext') to 'MyNamespace.MyEntities' 无法将“ ctx”(其实际类型为“ System.Data.Objects.ObjectContext”)转换为“ MyNamespace.MyEntities”

I would like to be able to use ctx as if it were an instance of MyEntities. 我希望能够像使用MyEntities一样使用ctx。 That would permit me to access the EF generated entities (ctx.entity1, ctx.entity2). 那将允许我访问EF生成的实体(ctx.entity1,ctx.entity2)。 Is there another way of doing this? 还有另一种方法吗?

You can't cast an object to just any type that you feel like. 您不能将对象强制转换为您喜欢的任何类型。 It actually has to be of that type. 它实际上必须是这种类型的。

It looks like what you are really trying to do is pass a connection string to your MyEntities class. 看起来您真正想做的是将连接字符串传递给MyEntities类。 Assuming the generated code does not provide one already, just add a new partial class with a constructor that takes a string and pass it to the base ObjectContext . 假设生成的代码尚不提供,只需添加一个新的带有构造函数的部分类,该构造函数接受一个字符串并将其传递给基本ObjectContext

public partial class MyEntities : ObjectContext 
{
    public MyEntities(string connectionString) : base(connectionString)
    { }
}

Then use this code: 然后使用以下代码:

var ctx = new MyEntities(entityConnectionString);

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

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