How to create immutable objects in C#?

后端 未结 8 477
有刺的猬
有刺的猬 2020-12-23 20:26

In a question about Best practices for C# pattern validation, the highest voted answer says:

I tend to perform all of my validation in the constructor

8条回答
  •  情深已故
    2020-12-23 21:04

    This question has two aspects:

    1. Immutable type when you instantiate object
    2. Immutable type when EF instantiate object

    The first aspect demands sturcture like this:

    public class MyClass
    {
      private readonly string _myString;
      public string MyString
      {
        get
        {
          return _myString;
        }
      }
    
      public MyClass(string myString)
      {
        // do some validation here
    
        _myString = myString;
      }
    }
    

    Now the problem - EF. EF requires parameterless constructor and EF must have setters on properties. I asked very similar question here.

    Your type must look like:

    public class MyClass
    {
      private string _myString;
      public string MyString
      {
        get
        {
          return _myString;
        }
        private set
        {
          _myString = value;
        }
      }
    
      public MyClass(string myString)
      {
        // do some validation here
    
        _myString = myString;
      }
    
      // Not sure if you can change accessibility of constructor - I can try it later
      public MyClass()
      {}
    }
    

    You must also inform EF about private setter of MyString property - this is configured in properties of enitity in EDMX file. Obviously there will be no validation when EF will materialize objects from DB. Also you will not be able to use methods like ObjectContext.CreateObject (you will not be able to fill the object).

    Entity Object T4 template and default code generation create factory method CreateMyClass instead of constructor with paremeters. POCO T4 template doesn't generate factory method.

    I didn't try this with EF Code first.

提交回复
热议问题