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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With