Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF: using backing field for setting property value

Is there a way to make EF use backing field when setting the values of property instead of property setter?

The reason I'm asking is that in setter there might be a logic that I don't want to be called every time an object is returned from database.

For ex:

class SomeClass
{
    int _prop;

    public Prop
    {
        get { return _prop;}
        set 
        {
            CustomValidation(value);

            _prop = value; 
        }
    }  
}

In the above sample, CustomValidation() is called on setting the value. There is no need to call this validation when returning objects from db, since those objects were validated on creation/validation.

like image 809
Markus Avatar asked Jul 09 '26 04:07

Markus


1 Answers

No, currently you can't map the column directly to a field. It has been discussed last year, but I'm not sure whether this will be part of future release or not. Check this article for further explanation. This is the code excerpt of the design.

modelBuilder
   .Entity<Blog>()
   .Property(b => b.Title)
   .UseBackingField("_theTitle");

The workaround would be creating a domain object or adding unmapped property that will be used in the front end for creation or validation.

public int Prop { get; set; }
[NotMapped]
public int ValidatedProp // bind to this property in the front end
{
   get { return Prop; } 
   set 
   {
       CustomValidation(value);
       Prop = value;
   }
}
like image 60
Yuliam Chandra Avatar answered Jul 11 '26 21:07

Yuliam Chandra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!