Readonly properties that NHibernate can work with

My domain classes have collections that look like this:

private List<Foo> _foos = new List<Foo>();
public virtual ReadOnlyCollection<Foo> Foos { get { return _foos.AsReadOnly(); } }

This gives me only ready-made collections that can be modified from the class (i.e. using the _foos field).

This collection is displayed as follows (Fluent NHibernate):

HasMany(x => x.Foos).KeyColumn("ParentClassId").Cascade.All().Inverse().Access.CamelCaseField(Prefix.Underscore);

Now when I try to use this collection, I get:

Cannot pass an object of type "NHibernate.Collection.Generic.PersistentGenericBag 1[Foo]' to type 'System.Collections.Generic.List1 [Foo]".

According to Unable to pass an object of type NHibernate.Collection.Generic.PersistentGenericBag to the list , this is because the collection must be exposed by NHibernate as an interface, so that NHibernate can enter one of its own collection classes.

IList , , , AsReadOnly(), , .

- , , , , , ?

+3
4

AsReadOnly() - ReadOnlyCollection.

private IList<Foo> _foos = new List<Foo>();
public virtual ReadOnlyCollection<Foo> Foos { get { return new ReadOnlyCollection<Foo>(_foos); } }

.

+7

- , IEnumerable<T>. , IList. , .

+4

- , IList ( ) Automapping, Foos / IList "NHibernate-friendly", ReadOnlyCollection, Foos.

- :

    protected IList<Foo> MappableFoos { get; set; }
    public ReadOnlyCollection<Foo> ReadOnlyFoos { get { return new ReadOnlyCollection<Foo>(MappableFoos) } }

    // Mapping file
    HasMany(x => x.MappableFoos ).KeyColumn("ParentClassId").Cascade.All().Inverse().Access.CamelCaseField(Prefix.Underscore);

Thus, the only property displayed will be the one I funny called " ReadOnlyFoos ".

+3
source

Think of exhibiting a collection as IEnumerableinstead ReadOnlyCollection; it essentially gives you the same level of protection without associating your model with a specific collection implementation. See this article for further discussion.

0
source

Source: https://habr.com/ru/post/1756929/


All Articles