简体   繁体   中英

Entity Framework - Custom logic in property setter

Using an EF, Code First. In my class I have properties Quantity, Price and Amount. In setters of the first 2 properties I want to add logic to calculate amount. This works ok, but when I load entity next time, and Entity Framework fills properties with database values, than this custom logic is implemented too - and this is not good. How do you think is there any to implement custom logic only when user actually changes the value and not during object initialization?

create ViewModel Class with 3 Properties

  1. Quantity{get;set}

  2. Price{get;set}

  3. Amount{get;}

Use INotifyPropertyChanged to Notify changes In Property.

public int Quantity
{
     get { return quantity; }
     set
     {
        quantity= value;
        NotifyPropertyChanged("Quantity");
        NotifyPropertyChanged("Amount");
     }
 }

public int Price
{
     get { return price; }
     set
     {
         price= value;
         NotifyPropertyChanged("Price");
         NotifyPropertyChanged("Amount");
     }
}

public long Amount
{
    get { return (Amount*Price); }
}

Change Any Property ie Quantity or Price, Amount will Automatically Updated with NotifyPropertyChanged

Update Property Logic can be written in Model Class

Try to implement this logic in controller action. Show us some code - it will be easier to find out what kind of logic you'd like to add.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM