简体   繁体   English

检测何时在实体框架中初始化POCO实体

[英]Detecting when POCO entities are being initialized in Entity Framework

Let's say I have a POCO with a property as such 假设我有一个POCO具有这样的属性

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; 当对象由EF初始化时,我只希望设置_firstName ,而别无其他,只有在对象初始化之后,我才希望集合运行其余的// DO STUFF; .

Why don't you simply 你为什么不简单

  1. Declare the property setter as protected ; 宣布财产保护者为protected保护者; and
  2. Expose your // DO STUFF behavior as a proper method SetFirstName(string firstName) ? 将您的// DO STUFF行为公开为适当的方法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. 更清洁,根本不需要“破解” EF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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