NHibernate: could not initialize a collection: - asp.net-mvc

I am struggling with NHibernate. I have a little ASP MVC website. I managed to setup NHibernate but when I want to retrieve data I get this error:
Additional information: could not initialize a collection: [Lore.Models.DatabaseModels.Statue.Keywords#1]
[SQL: SELECT keywords0_.IdStatueKeyword as IdStatue1_1_, keywords0_.IdKeyword as IdKeyword1_, keyword1_.IdKeyword as IdKeyword4_0_, keyword1_.Name as Name4_0_,
keyword1_.Description as Descript8_4_0_
FROM StatueKeyword keywords0_ left outer join Statue keyword1_ on keywords0_.IdKeyword=keyword1_.IdKeyword
WHERE keywords0_.IdStatueKeyword=?]
Also I am not sure if I implemented the many-to-many relationship right. This is my table structure:
Statue
IdStatue
Name
Keyword
IdKeyword
Name
StatueKeyword
IdStatueKeyword
IdStatue
IdKeyword
Statue Class:
public class Statue
{
public Statue()
{
Keywords = new List<Keyword>();
}
public int IdStatue { get; set; }
public string Name { get; set; }
public IList<Keyword> Keywords { get; set; }
}
Keyword Class
public class Keyword
{
public int IdKeyword { get; set; }
public string Name { get; set; }
}
Statue hbm file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Lore.Models.DatabaseModels" assembly="Lore">
<class name="Statue" table="Statue" lazy="false" >
<id name="IdStatue" column="IdStatue">
<generator class="identity" />
</id>
<property name="Name" column="Name" not-null="true" type="System.String" />
<bag name="Keywords" table="StatueKeyword" lazy="false">
<key column="IdStatueKeyword"/>
<many-to-many class="Keyword" column="IdKeyword"/>
</bag>
</class>
</hibernate-mapping>
Keyword hbm file
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Lore.Models.DatabaseModels" assembly="Lore">
<class name="Keyword" table="Statue" lazy="false" >
<id name="IdKeyword" column="IdKeyword">
<generator class="identity" />
</id>
<property name="Name" column="Name" not-null="true" type="System.String" />
<property name="Description" column="Description" not-null="true" type="System.String" />
</class>
</hibernate-mapping>
I need to make this website for a master thesis so any help is much appreciated!

The issue should/could be in the <key> mapping:
<bag name="Keywords" table="StatueKeyword" lazy="false">
<!-- <key> is representing column where current Statue ID should be searched
while the below one seems to be the ID column of the pairing table
so instead of this
<key column="IdStatueKeyword"/>
use this: -->
<key column="IdStatue"/>
<many-to-many class="Keyword" column="IdKeyword"/>
</bag>
Also check these:
6.3. Collections of Values and Many-To-Many Associations
23.2. Author/Work - documented example with many-to-many
Small cite:
The foreign key from the collection table to the table of the owning class is declared using a <key> element.
Another tip, if you do have an ID column of the pairing table, you should try to use augmented feature:
6.7. Using an <idbag>
Another cite from doc about idbag:
Note that the update performance of an <idbag> is much better than a regular <bag>! NHibernate can locate individual rows efficiently and update or delete them individually, just like a list, map or set.
Finally, I (personally) would descourage you from using many-to-many. My view is, that it is better to avoid it. See: 24. Best Practices (a cite:)
Don't use exotic association mappings.
Good usecases for a real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-to-many associations to an intermediate link class. In fact, we think that most associations are one-to-many and many-to-one, you should be careful when using any other association style and ask yourself if it is really neccessary.
Maybe later also check these:
Am I doing many to many incorrectly when using fluent nhibernate?
How to create NHibernate HasManyToMany relation
many-to-many with extra columns nhibernate
Nhibernate: How to represent Many-To-Many relationships with One-to-Many relationships?

Related

Error mapping optionset on CRM 365 virtual entities

When mapping an optionset on a virtual entity to its external data source got the following error:
Type mismatch of the external attribute of type ‘System.Nullable`1[System.Int32]’ expected a 'System.Nullable`1[[System.Int32, Microsoft.Xrm.DataProvider.OData.614d0bd27de7e9119c27005056876672.e98901a683e7e9119c27005056876672, Version=1.1.20.0, Culture=neutral, PublicKeyToken=null]]'
Thanks in advance
one cannot map using Int32, hence your error. Using virtual entities in D365 one has to use an enumeration for setting up and mapping optionsets. View the schema from your odata endpoint using $metadata:
example : https://yourowndatasource.azurewebsites.net/$metadata
it will return something like the below, find your defined schema enumtypes :
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
<edmx:DataServices>
<Schema Namespace="AK.IG.VirtualEntity.DataSource.Models" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EnumType Name="ak_Lead_EventTypeCode">
<Member Name="EugenesCode" Value="821220006" />
<Member Name="LeadSource" Value="821220001" />
<Member Name="LeadGenProcess" 821220001="3" />
...
</EnumType>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
With that use exactly the naming convention :
EnumType.Name
Member Name

NLog extensibility - How to add custom field using ExtendValues?

I try to add some custom fields to NLog using extensibility.
Part of my nlog.config file looks like that : (simplified for exhibit)
<nlog>
<extensions>
<add assembly="Logzio.DotNet.NLog"/>
</extensions>
<variable name="currentUser" value="test" />
<targets async="true">
<target name="logzio" type="Logzio" token="myToken">
<contextproperty name="currentUser" layout="${currentUser}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logzio" />
</rules>
</nlog>
In every controller, I have something like that (I'm using ASP.NET MVC5)
private static Logger logger = LogManager.GetCurrentClassLogger();
Then I send my logs to logzio using
logger.Fatal("Something bad happens");
Right now, currentUser always have the value test, which is logical.
However, despite of the documentation, I don't understand how to dynamically change currentUser value by the ID of my current logged user.
Should I create a sort of factory ? (if yes, how ? I'm not at ease with factories)
Should I change my logger variable ? If so, how ?
A piece of code would be extremly welcome.
Thank you for pointing my out where I'm wrong
EDIT
After #Rolf's answer, I've created this custom layout renderer
[LayoutRenderer("custom-layout")]
public class CustomLayoutRenderer : LayoutRenderer
{
public string IdUser { get; set; }
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
logEvent.Properties.Add("currentUser", "HowToPassCustomDataHere?");
builder.Append("test from custom-layout");
}
}
and I changed the nlog.config accordingly, adding
layout="${message} ${custom-layout}"
to my <target>
However, I still don't understand how to pass custom value to currentUser. In logz.io, I have "HowToPassCustomDataHere?" as a value of currentUser.
(BTW, ${aspnet-user-identity} is great and works fine ; however I'd like to understand how to pass a custom value to my layout renderer. In my case, something like ${aspnet-user-id})
You can try one of these NLog layoutrenderers to acquire the current username:
${aspnet-user-identity} Wiki
${windows-identity} Wiki
You can also create your own custom NLog LayoutRenderer: https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer
Example of how to provide it as currentUser:
<target name="logzio" type="Logzio" token="myToken">
<contextproperty name="currentUser" layout="${aspnet-user-identity}" />
</target>

Read ProblemSection From CCD Using MDHT

I am trying to parse problem section in CCD using MDHT. The XML code I am trying to parse is:
<entry>
<act classCode="ACT" moodCode="EVN">
<templateId root="2.16.840.1.113883.10.20.22.4.3" />
<id root="2.16.840.1.113883.3.441" extension="85cec11c26ff475fac469cc9fa7a040c" />
<code code="CONC" codeSystem="2.16.840.1.113883.5.6" />
<statusCode code="active" />
<effectiveTime nullFlavor="UNK">
<low value="20110925000000" />
<high nullFlavor="UNK" />
</effectiveTime>
<entryRelationship typeCode="SUBJ" inversionInd="false">
<observation classCode="OBS" moodCode="EVN" negationInd="false">
<templateId root="2.16.840.1.113883.10.20.22.4.4" />
<id root="2.16.840.1.113883.3.441.1.50.300011.51.26604.61" extension="1348" />
<code nullFlavor="NA" />
<text>Asthma<reference value="#ref_d910f32f622b4615970569407d739ca6_problem_name_1" />
</text>
<statusCode code="completed" />
<effectiveTime nullFlavor="UNK">
<low value="20110925000000" />
<high nullFlavor="UNK" />
</effectiveTime>
<value xsi:type="CD" nullFlavor="UNK">
<translation code="195967001" displayName="Asthma" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT">
<originalText>
<reference value="#ref_d910f32f622b4615970569407d739ca6_problem_name_1" />
</originalText>
</translation>
</value>
I want to read the translation tag (displayName="Asthma"). I want to read asthma, its code value and code system.
But in MDHT I can't get translation tag inside value tag. I am doing get as:
entry.getAct().getEntryRelationships().get(0).getObservation().getValues().get(0) //no translation tag.
One of the advantages of using MDHT versus other JAVA/XML generations is we generate domain specific classes to help you navigate the document a bit more effectively
You should avoid using specific get() and generic getObservation because the underlying CDA standard constrains what is required but producers are able to place any sort of observation etc within the document. Here is a sample snippet to walk the problem section
The observation class itself and as such the problem observation value is a collection of ANY which need to properly cast to get to the CD type which in turn would have the translation property you are looking for.
hth
Sean
ProblemSection ps = ...
for (ProblemConcernAct cpc : ps.getConsolProblemConcerns()) {
for (ProblemObservation pos : cpc.getProblemObservations()) {
for (ANY any : pos.getValues()) {
if (any instanceof CD) {
CD code = (CD) any;
for (CD translationCode : code.getTranslations()) {
System.out.println(translationCode.getCode());
}
}
}
}
}

mogenerator doesn't generate any entities even though datamodel contains entities. Reports "No entities found in model. No files will be generated."

I'm trying to get mogenerator (1.26 latest) to generate some boiler plate classes from a core data model (xcdatamodel) and it reports:
No entities found in model. No files will be generated.
(model description: (<NSManagedObjectModel: 0x10012e410>) isEditable 1, entities {
}, fetch request templates {
})
Even though the contents of the xcdatamodel clearly exist
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model name="" userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="1487" systemVersion="11E53" minimumToolsVersion="Xcode 4.3" macOSVersion="Automatic" iOSVersion="Automatic">
<entity name="Chair" representedClassName="Chair" syncable="YES">
<attribute name="name" attributeType="String" maxValueString="50" syncable="YES"/>
</entity>
...
What am I doing wrong?
I am using Xcode 4.4.1 and mogenerator 1.26
This is a quote from http://raptureinvenice.com/getting-started-with-mogenerator/
When you create entities in your data model, be sure to populate the
“Class” field with the same name as the entity.
So what you have to do is:
Open your data model
Select your entity
In the right panel, select the Data Model Inspector (3rd one)
Edit the "Class" field with the same name as the "Name" field

NHibernate: No persister error

In my quest to further my knowledge, I'm trying to get get NHibernate running.
I have the following structure to my solution
Core Class Library Project
Infrastructure Class Library Project
MVC Application Project
Test Project
In my Core project I have created the following entity:
using System;
namespace Core.Domain.Model
{
public class Category
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
}
}
In my Infrastructure Project I have the following mapping:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Core.Domain.Model"
assembly="Core">
<class name="Category" table="Categories" dynamic-update="true">
<cache usage="read-write"/>
<id name="Id" column="Id" type="Guid">
<generator class="guid"/>
</id>
<property name="Name" length="100"/>
</class>
</hibernate-mapping>
With the following config file:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">server=xxxx;database=xxxx;Integrated Security=true;</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="cache.use_query_cache">false</property>
<property name="adonet.batch_size">100</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<mapping assembly="Infrastructure" />
</session-factory>
</hibernate-configuration>
In my test project, I have the following Test
[TestMethod]
[DeploymentItem("hibernate.cfg.xml")]
public void CanCreateCategory()
{
IRepository<Category> repo = new CategoryRepository();
Category category = new Category();
category.Name = "ASP.NET";
repo.Save(category);
}
I get the following error when I try to run the test:
Test method Volunteer.Tests.CategoryTests.CanCreateCategory threw exception: NHibernate.MappingException: No persister for: Core.Domain.Model.Category.
Any help would be greatly appreciated. I do have the cfg build action set to embedded resource.
Thanks!
The Build Action of the XML mapping file must be set to Embedded Resource in the Infrastructure assembly. When you use the following instruction in your config file: <mapping assembly="Infrastructure" /> it will look for mappings as embedded resources in this assembly.
I am guessing the problem is that your configuring your SessionFactory in your Test assembly without telling it that your mappings are in your Core assembly, something like
ISessionFactory factory = new Configuration().Configure()
.AddAssembly(typeof(Category).Assembly) <========***
.BuildSessionFactory();
If that doesn't help, post your configuration code.
Cheers,
Berryl

Resources