The short answer is no . And it would be strange that you could do this (well, NHibernate can set private class classes, which means that you can expose it using a public property encapsulating the field as a read-only collection ... well, you can get around this situation in EF too: Entity Framework Many for many using the object . By the way, I would not offer you this approach, because how could you add new parents if this is a private property? )
In any case, I believe that the domain object should be read-write, because at the end of the day, the domain object describes the object in the domain, and you should have access to it and modify it.
An alternative solution is an interface to display Parents as IReadOnlyList<Person> , as well as IPerson with all Person members except Parents , and returns Person as IPerson :
public interface IHasParents { IReadOnlyList<Person> Parents { get; } } public interface IPerson : IHasParents { long Id { get; set; } string Name { get; set; } }
And implement IPerson implicitly on Person , with the exception of Parents , which will be implemented explicitly. When you need to return Person somewhere, you return IPerson instead of Person :
public IPerson CreatePerson(string name, IEnumerable<Persons> parents) { Person person = new Person { Name = name, Parents = parents };
It can be argued that you can disable IPerson before Person , but at that moment I would say that you need to follow your own encoding rules: if you determined that you never return Person but IPerson , then I would do it this way in the whole database code, and if you need the Parents property to write, then you will return Person instead (and you will avoid throwing later!).
MatΓas Fidemraizer
source share