Search code examples
entity-frameworkentity-framework-5ef-model-first

Entity Framework 5 model first - Where is IDisposable gone?


In Entity Framework 5 model first, there seem to be some breaking changes due to the way the class files are generated (No more code generation, but T4 templates)

2 examples:

  • The generated context file doesn't implement IDisposable anymore
  • There isn't a constructor which takes a connectionstring anymore

Are there more breaking changes? And what is the solution to them?


Solution

  • The default code generated from a model in Entity Framework 5 now inherits DbContext instead of ObjectContext.

    This still implements IDisposable, but if you're getting an error from a line of code similar to this:

    using (var mymodel = new MyModelContext()) { ... }
    

    ...complaining about not implementing IDisposable, then your problem is most likely that your model is defined in a separate assembly that references EF5 and you have not added an EF5 reference to your project.

    As Ladislav Mrnka has already mentioned in his answer, if you want to pass a connection string to the constructor you have to create your own constructor manually to do this.

    If you want to switch Entity Framework back to the older style of generated code, which will automatically generate the constructor you're looking for, then follow these steps:

    1. Click on the designer surface of your EDMX file, and look at the properties window. Find a property called "Code Generation Strategy" and set this to "Default" instead of "None". This will tell Visual Studio to start creating the code for your object model in MyModel.Designer.cs in one big file, this time using ObjectContext instead of DbContext.
    2. Delete the following sub files from below your EDMX file: MyModel.Context.tt, MyModel.tt. These are the auto generated files that you don't want anymore. If you don't delete them you'll get class naming conflicts because your objects will be created twice.