In this answer to a recent question, I was advised to
‘be wary of making every property in your domain model have public getters and setters. That can lead you to an anemic domain model.’
However I then encounter the problem that an entity with private setters, like this:
public class Phrase { public int PhraseId { get; private set; } public string PhraseText { get; private set; } }
cannot be JSON-serialized from a View to a controller (using ASP.NET MVC). This is due to the private setter.
How would you allow serialization with private setters?
I don’t know if you can override the deserialization process with MVC, but note that
DataContractSerializersupports non-public accessors, and there is a JSON version:DataContractJsonSerializer– maybe worth a look?Personally, though, I’d just accept the public setter in this case… this is a pretty common feature of .NET DTOs and .NET-based serializations. The immutable/factory pattern, while common in java, hasn’t really taken as much hold in .NET; I can’t say I mind overly.