简体   繁体   中英

Downcast ObjectContext to Entities collection

I have an entity model created with a database-first approach in 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. This forces me to work directly with the ObjectContext class, passing in a valid EF connection string. Here is how I instantiate an ObjectContext:

var ctx = new ObjectContext(entityConnectionString);

This executes correctly, and I can succesfully run SQL commands against the db using ctx.ExecuteStoreCommand().

The name of my generated model is MyEntities. This is derived from ObjectContext, as can be seen in MyEntities.Designer.cs:

public partial class MyEntities : ObjectContext

However, if I try to cast ctx to MyEntities object:

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'

I would like to be able to use ctx as if it were an instance of MyEntities. That would permit me to access the EF generated entities (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. 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 .

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

Then use this code:

var ctx = new MyEntities(entityConnectionString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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