Overriding code-generated DbContext constructor

前端 未结 5 1353
花落未央
花落未央 2021-01-11 14:57

I\'m sure I\'ve done this before at some stage, but I can\'t figure out how to now! My scenario:

// This is generated from EDMX
public partial class HOLDbEnt         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-11 15:20

    I up-voted the previous accepted answer because it is a fairly elegant way of doing it. However another approach would be to modify the T4 template that generates the dbContext Class.

    When using EF DB first you have a .edmx file and under that you have an [Entity].Context.tt file. Go into that file and remove (or modify) the following code:

    public <#=code.Escape(container)#>()
            : base("name=<#=container.Name#>")
        {
    <#
    if (!loader.IsLazyLoadingEnabled(container))
    {
    #>
            this.Configuration.LazyLoadingEnabled = false;
    <#
    }
    
    foreach (var entitySet in container.BaseEntitySets.OfType())
    {
        // Note: the DbSet members are defined below such that the getter and
        // setter always have the same accessibility as the DbSet definition
        if (Accessibility.ForReadOnlyProperty(entitySet) != "public")
        {
    #>
            <#=codeStringGenerator.DbSetInitializer(entitySet)#>
    <#
        }
    }
    #>
    

    now your context class will generate without a constructor, so you should be able to go and create one in an extended class.

提交回复
热议问题