Trying to access a discriminator type field in NHibernate

I have a class base on my map, it inherited two new classes

<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Business" namespace="Business.Test"> <class name="BaseExample" table="base_example" abstract="true" discriminator-value="0"> <id name="Id" column="id" type="Int64" unsaved-value="0"> <generator class="native"/> </id> <discriminator column="domain" type="Int16" not-null="true" force="true" /> .... .... </class> </hibernate-mapping> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Business" namespace="Business.Test"> <subclass name="Example1" extends="BaseExample" discriminator-value="1"> .... .... </subclass> </hibernate-mapping> 

everything works fine, but if I ask about this field, for example:

 var Clients = ClientFactory.GetAll().Where(c => c.UserData.BaseExample.Domain == 1); 

throw this exception: Exception Message: failed to resolve property: Domain of: Business.Entities.BaseExample

how to determine if this applies to one class?

+4
source share
2 answers

Discriminators are designed for use behind the scenes from NHibernate (see Rippo example). The idea is that you are requesting a class , and the corresponding requestor from this class mapping is entered into the request.

However, if for some reason you need this information in a property, it should include it as a property. It means

 <class name="BaseExample" table="base_example" abstract="true" discriminator-value="0"> <id name="Id" column="id" type="Int64" unsaved-value="0"> <generator class="native"/> </id> <discriminator column="domain" type="Int16" not-null="true" force="true" /> <property name="domain" column="domain" type="Int16" update="false" insert="false" /> .... .... </class> 

it is important that the declaration be declared as readonly ( update="false" insert="false" ), as it is a column that is fully managed by nhibernate.

+8
source

Using QueryOver to get all the entries in the base_example table for the BaseExample class, you will do the following: -

 session.QueryOver<BaseExample>().List(); 

to get all the records of Example1 you do it

 session.QueryOver<Example1>().List(); 

to get all the entries in Example2 : -

 session.QueryOver<Example2>().List(); 

In other words, NHibernate is smart enough to add a where Domain=1 or Domain=2 clause in the query for you automatically.

It should also be noted if you want all the records from the base table to have a loop, then you can do this: -

 var list = session.QueryOver<BaseExample>().List(); foreach(var item in list) { if (item is Example1) Output(Example1) //Do something with Example1 if (item is Example2) Output(Example2) //Do something with Example2 } 
+1
source

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


All Articles