简体   繁体   中英

Detecting when POCO entities are being initialized in Entity Framework

Let's say I have a POCO with a property as such

public class Person
{
    private string _firstName;
    public string FirstName
    {
       get { return _firstName; }
       set
       {
           _firstName = value;
           // DO STUFF;
       }
    }
}

When the object is being initialized by EF, I only want _firstName to be set and nothing else, only after the object is initialized do I want a set to run the rest // DO STUFF; .

Why don't you simply

  1. Declare the property setter as protected ; and
  2. Expose your // DO STUFF behavior as a proper method SetFirstName(string firstName) ?

Something like this:

public class Person
{
    public string FirstName { get; protected set; }

    public string SetFirstName(string value)
    {
       _firstName = value;
       // DO STUFF;
    }
}

Much cleaner, don't need to "hack" EF at all.

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