EF: Using a Backing Field to Set a Property Value

Is there a way to make the field support using EF when setting property values ​​instead of a setter property?

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

For ex:

class SomeClass
{
    int _prop;

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

            _prop = value; 
        }
    }  
}

      

The above example calls CustomValidation () when setting a value. There is no need to call this check when returning objects from db as these objects were checked on creation / validation.

+3


source to share


1 answer


No, you cannot currently map a column directly to a field. This was discussed last year, but I'm not sure if it will be part of a future release or not. Check out this article for further explanation. This is a snippet of the project code.

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

      



A workaround would be to create a domain object or add an untagged property that will be used in the interface to create or validate.

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;
   }
}

      

+1


source







All Articles