There are options you have:
1. ORMs can work with private fields.
As I know, ORMs (e.g. Entity Framework, NHibernate) can set properties via non-public setters.
There is an example that proves it for Entity Framework - Entity Framework, Private Constructors and Private Setters.
If you use NHibernate your setters should be public/protected virtual
/protected internal virtual
or private
backing field can be used. You can find more information in the Property Access strategies in NHibernate SO question.
2. Reflection can be used.
It can be used to get access to private fields/properties also. It is possible to set private property via reflection.
3. It is not a bad practice to have public constructor to construct your entity.
Declaring public constructors containing all of the fields doesn't seems right. I might have several models to fill in, this means I have to define several constructors with different sets of parameters.
Your Domain Entities need only one public constructor with full list of properties they have. It is enough to have only one constructor in spite of having several models to fill in. It is a responsibility of repository to invoke constructor and map model into its parameters correctly.
Edit:
4. Automapper can be used.
The following test shows that AutoMapper can map properties via private setters.
[TestClass]
public class AutomapperTest
{
[TestMethod]
public void Test()
{
// arrange
Mapper.CreateMap<AModel, A>();
var model = new AModel { Value = 100 };
//act
var entity = Mapper.Map<A>(model);
// assert
entity.Value.Should().Be(100);
entity.Value.Should().Be(model.Value);
}
}
public class AModel
{
public int Value { get; set; }
}
public class A
{
public int Value { get; private set; }
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…