Domanda

I´m building a Windows Forms aplication using LINQ to SQL. I´m using the auto generated code from the dbml file.

Visual studio generated this code for the CNPJ property from my table:

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CNPJ", DbType="VarChar(20) NOT NULL", CanBeNull=false)]
public string CNPJ
{
get
{
  return this._CNPJ;
}
set
{ 
  if ((this._CNPJ != value))
  {
     this.OnCNPJChanging(value);
     this.SendPropertyChanging();
     this._CNPJ = value;
     this.SendPropertyChanged("CNPJ");
     this.OnCNPJChanged();
  }
 } 
}

and what I wanted is this:

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CNPJ", DbType="VarChar(20) NOT NULL", CanBeNull=false)]
public string CNPJ
{
get
{
  return APPLY_FORMAT(this._CNPJ);//Changed here
}
set
{ 
  if ((this._CNPJ != value))
  {
     this.OnCNPJChanging(value);
     this.SendPropertyChanging();
     this._CNPJ = REMOVE_FORMAT(value); /// Changed here
     this.SendPropertyChanged("CNPJ");
     this.OnCNPJChanged();
  }
 } 
}

But I will lose this changes when the code is re-generated. Question is: what is the right way to accomplish this behavior (inherit and override, capture change event, other ) ?

if you´re curious, CNPJ is the brazilin business identification number, provided by the government.

È stato utile?

Soluzione

Rather than trying to change the existing property, create a new property.

public partial class YourClass
{
    public string FORMATTED_CNPJ
    {
        get
        {
            return APPLY_FORMAT(this._CNPJ); 
        }
        set
        {
            this.CNPJ = REMOVE_FORMAT(value);
        }
    }
}

If you don't want anyone to access the underlying CNPJ property you can set it to private in the designer (the access modifier combobox in the column properties window). You can even rename that property to _CNPJ, make it private, and then name your 'wrapper' property above CNPJ if you want to avoid any breaking changes.

Altri suggerimenti

LINQ to SQL creates the classes as partial classes. You can create another partial class in a different file but with the same class name and then you can change the behaviour.

public partial class YourClass
{
    partial void OnCNPJChanged()
    {
        this._CNPJ = REMOVE_FORMAT(value);
    }
}

See here for more information.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top