Pop
Pop

Reputation: 525

Automate custom code generation when "Run Custom Tool" on tt file

I have this edmx, database first, in project "DAL".
But the tt file from edmx is in another project "DomainModel".
Both projects are in the same solution.

Now, whenever I created new table in database, update model from database, I have to manually re-insert IEntity and public EntityState EntityState { get; set; } in every table class generated from "Run Custom Tool" on tt file.

public partial class newTable : IEntity
{
    public EntityState EntityState { get; set; }
}

public partial class oldTable : IEntity
{
    public EntityState EntityState { get; set; }
}

I also have to manually re-insert Configuration.LazyLoadingEnabled = false; and Configuration.ProxyCreationEnabled = false; in the following code

public partial class myEntities : DbContext
{
    public myEntities()
        : base("name=myEntities")
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }
}

is there anyway for me to automate these? especially the first part, with hundred of tables.

Upvotes: 0

Views: 219

Answers (1)

fenixil
fenixil

Reputation: 2124

You may try to tweak tt, however I'd recommend you to utilize partial feature, it is there for purpose :). Put put all amendments to the separate file which is not replaced on every model update. This is still manual or semi-manual work, but you need to do that only once and then you'll need to update it only for new tables.

// DbModelPatches.cs
public partial class newTable : IEntity
{
    public EntityState EntityState { get; set; }
}

public partial class oldTable : IEntity
{
    public EntityState EntityState { get; set; }
}

If default constructor is generate by tt you cannot replace it in partial file, but you can define another one, parametreized, and put all changes there.

public partial class myEntities : DbContext
{
    public myEntities(string name)
        : base("name={name}")
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

   // or static factory method:
   public static myEntities CreateContext() 
   {
      var res = new myEntities();
      res.Configuration.LazyLoadingEnabled = false;
      res.Configuration.ProxyCreationEnabled = false;
      return res;
   }
}

Upvotes: 1

Related Questions