Thursday, February 18, 2016

EF error - Type '{your_entity_name}' already defines a member called '.ctor' with the same parameter types


Couple of days ago I have decided to set custom database connection string to my entity framework data model in one of my project. Then I have created a partial class with the same name of my entity and modify connection string name of base parameter. like example below -


public partial class DBPointOfSalesEntities
{
  public DBPointOfSalesEntities()
           : base(my.GetEntityConnectionString)
      {
      }
}


and deleted default constructor from [model].cs file.

But the problem is, whenever I update my model, it generates default constructor with default base parameter value. And occurs error for ambiguous constructor name as I have created above.

Then after googling, I found a nice solution - there is a [model].tt file which is called T4 template. Entity model is generating its automatic code based on this template. There is a specific code snippet which is responsible for generating default constructor after updating model from database each time. following is that code snippet. I have just deleted those lines and my problem fixed.
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)#>
<#
  }
}
#>
   }



Happy coding...

No comments:

Post a Comment