C# .NET Immutable properties for Entity Framework, serializable classes, etc

An easy way to make properties immutable is to have private setters and pass the data as constructor parameter. Because entity framework needs a parameterless constructor, you need to provide oune, but you can make it private:


public class Immutable
{
   public string ImmutableProperty { get; private set;}
   
   // Parameterless constructor required for Entity framework serializer (and many other serializers too)
   private Immutable(){}
   
   public Immutable(string aData)
   {
      ImmutableProperty = aData;
   }
}

This is the easiest way to achive immutability using Entity Framework, and make posible to create Value-Objects (see Domain Driven Design by Eric Evans)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s