Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly Fields or Properties

Is there a way to have either a read only Field or a Property with no setter map to a database column with Entity Framework Code First?

I found both are ignored, example:

using System;

namespace App.Model
{
    public class Person
    {
        string _address1; // Private Field to back the Address Property

        public string Address1 // Public Property without a Setter
        {
            get { return _address1; }
        }


         public readonly string Address2; // Public Read Only Field
    }
}

Is there Fluent API call or another approach to accomplish?

like image 436
Josh Avatar asked May 24 '13 22:05

Josh


1 Answers

There's no way to make entities truly immutable, but you can use an inaccessible setter to stop users from modifying them, which might be good enough, depending on your situation:

public string Address1 // Public Property without a Setter
{
  get { return _address1; }
  internal set { _address1 = value; }
}

The Entity Framework will still be able to set the value, so it'll load properly, but once created the property will be more or less fixed.

(I recommend using an internal rather than private setter, so that you can still perform mappings with the Fluent API in your context or a configuration class, provided they're in the same assembly, or a friend assembly.)

like image 57
Jeremy Todd Avatar answered Oct 14 '22 01:10

Jeremy Todd