Search code examples
c#entity-frameworkgridviewmodelpresentation-layer

How can return a text based on value in database in EF6 using get method


I create a model using EF6 .My model is like this :

public partial class Good
{
    public Good()
    {
        this.InnoviceDetails = new HashSet<InvoiceDetail>();
    }

    public int Id { get; set; }
    public string Serial { get; set; }
    public string HasTax { get; set; }
    public string InitialAmount { get; set; }
    public string Group { get; set; }

    public virtual ICollection<InvoiceDetail> InnoviceDetails { get; set; }
}

One of the my columns is HasTax and the value of this is 1 and 0 ,but in mygridview i need to change these values (0,1). i mean if the value is 1 shows Yes and if it is 0 shows No.I want to do these using get method of my model ?Is it possible ?

Get method checks the values in database and return proper values to gridview or Presentation layer ?

Best regards


Solution

  • If you:

    1) Don't want to directly change your model or create views.
    2) Or add any additional properties that will be used only for binding-with-conversion.

    Then you are left with two main variants I could think of:

    1) Create a semi-wrapper that exposes your original model and additional special property for binding-with-conversion:

    public class ModelSemiWrapperBase<TModel> 
    {
       public ModelSemiWrapperBase(TModel model)
       {
           this.Model = model;
       }
       public TModel Model
       {
           get;
           private set;
       }
    }
    
    public class GoodSemiWrapper : ModelSemiWrapperBase<Good>
    {
        public String HasTax
        {
            get
            {
                return (this.Model.HasTax == 0) ? ("Yes") : ("No");
            }
            set {...}
        }
    }
    

    Just do not forget about INotifyPropertyChanged and changes notification. Also in this case you will have to manually add columns in the DataGridView.

    2) Handle events in the DataGridView:

    Something like How do I use a ValueConverter with Databinding in Winforms, just with dataGridView using the CellValueChanged, CellValidating, DataBindingComplete or other similar events.
    I am not even sure which events you should really use. And I'd not gone using such a way. It is too error-prone and it strongly bundles your dataGridView with validation and conversion logic.