How to extend an Entity Framework 6.1.3 generated

2019-03-02 23:57发布

问题:

Is it possible to extend an Entity Framework 6.1.3 generated class?

I have an existing database to which I have created an ADO.NET Entity Data Model, which in turn Visual Studio 2015 has generated a set of classes.

public partial class WebApplication1Entities : DbContext
{
    public WebApplication1Entities()
        : base("name=WebApplication1Entities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
}

I can manually override the WebApplication1Entities to allow a dynamic runtime connection as so:

    public WebApplication1Entities(string connectionString) : base(connectionString)
    {
    }

This however, involves editing the class that Visual Studio 2015 has generated, but should I wish to update the ADO.NET Entity Data Model in the future, Visual Studio will overwrite any manual changes I have made to the previous generated class and I'm back to square one, having to manually edit the generated class.

Is it possible to create a helper class or something similar to extend the existing WebApplication1Entities : DbContext, and allow the addition of the new overloaded method and also inherit the existing methods of the Visual Studio 2015 generated class such as virtual DbSets.

Any help would be much appreciated :-)

回答1:

As you see in the declaration

public partial class WebApplication1Entities : DbContext

this class is partial.

So you can create another *.cs file and put your code there (use the same namespace!):

public partial class WebApplication1Entities
{
     public WebApplication1Entities(string connectionString) : base(connectionString)
     {
     }        
}

So when the designer overwrites the file containing the "original" class, your code stays untouched.

More about partial classes and methods.