NHibrenate Could Not Load Type - nhibernate

I'm getting some very strange behavior with Linq to nHibernate.
I can retrieve all objects I want and I can add where clauses.
But in a very specific case I get the following exception:
Could not load type x.Foo.Bar.Bars. Possible cause: the assembly was
not loaded or not specified.
x.Foo.Bar.Bars is part of a piece of lambda expression in a where clause.
Where Bars is a collection of objects. The collection get filled perfectly when I just query without the where clause.
query.Where(x => x.Foo.Bar.Bars.Any(b => b.Name == "BarName"));
The stacktrace is this:
at NHibernate.Util.ReflectHelper.ClassForFullName(String classFullName)
And yes, my mapping files are embedded resources.
Part of the mapping:
<bag name ="Bars" inverse="true" lazy="false"
cascade="none" optimistic-lock="false"
access="Framework.NHibernate.Properties.EntityCollectionAccessor, Assembly">
<key column="BagId" />
<one-to-many class="Bar"/>
</bag>

access="Bars, Assembly" looks wrong. You don't want to define an access strategy that is implemented in the class Bars, do you?

Related

How to persist a subset of an object instead of the whole object?

I'm struggling with a NHibernate related problem where I could use some input.
Introduction:
I have a legacy database where the relational concepts have not really been applied.
In the database I have an OrderLine table which contains data for an order lines.
On top of that the table also contains all columns with Order specific information. This could for example be order number of a customer.
E.x. If i have 10 order lines - then I have 10 rows in my OrderLines table and each row has all the Order specific data e.g. order number or customer information.
I did not want to have the above structure in my code so a view was created for Orders so that I could map my Order in NHibernate which then has a set/bag of OrderLines which makes much more sense.
Mapping: (simplified)
<class name="Order" table="[view_Orders]">
<bag name="OrderLines">
</class>
<class name="OrderLine" table="OrderLines" />
The problem:
The complexity of the view makes it impossible to save to the view. When trying NHibernates throws this exception:
NHibernate.Exceptions.GenericADOException: could not insert: XXX ---> System.Data.SqlClient.SqlException: View or function 'view_Orders' is not updatable because the modification affects multiple base tables.
My NHibernate mapping is constructed as an Order object which has a "set or bag" of OrderLine objects. Ideally I would like NHibernate only to persist the set of OrderLine objects instead of the whole object.
Is there a way of achieving this? I have tried locking the object using different lock modes but it did not help me.
You can use mutable="false" to avoid the update and deletes as this article says:
Immutable classes, mutable="false", may not be updated or deleted by the application. This allows NHibernate to make some minor performance optimizations.
To avoid the insert you can use the following statement (Uses the proyection instead an insert command, dont forget use check="none"):
<sql-insert check="none">SELECT 1</sql-insert>
Here is a tested example:
<class name="Order" table="[view_Orders]" mutable="false">
<id name="OrderId" type="System.Guid">
<generator class="guid.comb"/> <!-- Change as you need -->
</id>
<!-- Other properties -->
<!-- <property name="GrandTotal"/> -->
<set name="OrderLines" lazy="true" inverse="true" cascade="all-delete-orphan">
<key column="OrderId"/>
<one-to-many class="OrderLine"/>
</set>
<sql-insert check="none">SELECT 1</sql-insert>
</class>
<class name="OrderLine" table="OrderLine">
<id name="OrderLineId" type="System.Guid">
<generator class="guid.comb"/> <!-- Change as you need -->
</id>
<!-- Other properties -->
<!-- <property name="OrderId"/>
<property name="GrandTotal"/>/> -->
</class>
In case I do understand your issue, the solution is surprisingly simple. We just would mark root object with dynamic-update="true"
<class name="Order" table="[view_Orders]" dynamic-update="true">
...
</class>
And then apply update="false" to every property or reference which we have in that Order class mapped to view:
...
<property name="Code" update="false"/>
...
<many-to-one name="Country" update="false />
But our collection will need the standard, even cascade mapping:
<class name="Order" table="[view_Orders]" dynamic-update="true">
<bag name="OrderLines"
lazy="true"
inverse="true"
batch-size="25"
cascade="all-delete-orphan" >
...
</bag>
... // other stuff is update="false"
</class>
And now code like this would do management of OrderLines, while not executing any updates on the root object Order
var session = ... // get ISession
// load root
var root = session.Get<Order>(123);
// if needed change existing line (pretend there is one)
root.OrderLines[0].Amount = 100;
// add new
var newOrder = ... // new order
root.OrderLines.Add(newOrder);
session.Save(root);
session.Flush();
And that is it. Cascade on the root object is doing what we need, while the update="false" is not updating it...
NOTE: Just interesting note - there is also class and collection
setting mutable="false", but it would not work here... as the
solution mentioned above (it is sad, because that would be more
elegant, but not working as expected...). See:
19.2.2. Strategy: read only
If your application needs to read but never modify instances of a persistent class, a read-only cache may be used. This is the simplest and best performing strategy. Its even perfectly safe for use in a cluster.
<class name="Eg.Immutable" mutable="false">

NHibernate custom collection type

I'm having an entity object called Patient and this entity is having a property called Visits which is of type VisitsCollection.
VisitsCollections is a child class of IList<Visit> but it also adds some custom logic to the collection (like auto ordering, some validation, notifications, etc..).
I need to use the custom collection type as it adds some data to the entities that are added to the collection and performs some other paperwork transparently.
Now I want to map that in NHibernate, so I've created:
<list name="Visits" lazy="true" fetch="select">
<key foreign-key="PatientId" />
<index column="Timestamp" />
<one-to-many class="Visit" not-found="ignore"/>
</list>
I'm getting an exception:
Unable to cast object of type 'NHibernate.Collection.PersistentList' to type '...VisitsCollection'
Whenever I'm accessing the visits property.
I've also tried to map it this way:
<list name="Visits" lazy="true" fetch="select" collection-type="VisitsCollection">
<key foreign-key="PatientId" />
<index column="Timestamp" />
<one-to-many class="Visit" not-found="ignore"/>
</list>
but still, I'm getting this exception:
Custom type does not implement UserCollectionType: .....VisitsCollection
I don't want to inherit my VisitsCollection from any NHibernate type as the collection class is part of a framework that I want it to be DAL-agnostic (as it will be used in many scenarios - not only with a database).
Any ideas on how to map this, preserving the structure of my code?
Thanks in advance.
I never use custom collection types, mainly because I'm lazy. NHibernate wants you to use a IUserCollectionType I believe, which requires a bit of plumbing.
Rather than that, my first stop would be to look at using extension methods as discussed by Billly McCafferty. But you have code written so...
Alternatively, you could map your collection as a component as discussed here by Colin Jack. This might be easier for your scenario?
Also check this SO thread.
I also vote up not to use custom collections. Anyway, you can do it via component.
<component name="Warehouses" class="Core.Domain.Collections.EntitySet`1[Core.Domain.OrgStructure.IWarehouseEntity,Core],Core">
<set name="_internalCollection" table="`WAREHOUSE`" cascade="save-update" access="field" generic="true" lazy="true" >
<key column="`WarehouseOrgId`" foreign-key="FK_OrgWarehouse" />
<!--This is used to set the type of the collection items-->
<one-to-many class="Domain.Model.OrgStructure.WarehouseEntity,Domain"/>
</set>
How to map NHibernate custom collection with fluentNHibernate?
Just for reference, here is how you could do it using FluentNHibernate
Whether we should or should not create a custom collection type is a separate topic IMHO
public class PatientOverride : IAutoMappingOverride<Patient>
{
public void Override(AutoMapping<Patient> mapping)
{
mapping.Component(
x => x.Visits,
part =>
{
part.HasMany(Reveal.Member<VisitsCollection, IEnumerable<Visit>>("backingFieldName")) // this is the backing field name for collection inside the VisitsCollection class
.KeyColumn("PatientId")
.Inverse(); // depends on your use case whether you need it or not
});
}
}

NHibernate - Lazy Loaded Collection

Should a lazy loaded collection in NHibernate ever give me a NullReferenceException? I'm getting an exception in a method like the following:
public void Test(ISession session, int id)
{
var entity = session.Load<MyEntity>(id);
entity.LazyLoadedCollection.Add(SomeItem);
}
The call to LazyLoadedCollection is throwing. My mapping looks like:
<bag lazy="true" table="MyTable">
<key>
<column name="LazyLoadedCollection" />
</key>
<many-to-many class="LazyLoadedItem">
<column name="LazyLoadedItemId" />
</many-to-many>
</bag>
Is this the expected behavior in NHibernate?
It's hard to say without seeing your class, but one thing you may not have realized is that you need to populate each collection in your class's constructor.
NHibernate will replace these collections with its own at certain times, but you still need to make sure they're initially populated with a HashedSet<T>, List<T>, or something else depending on the interface you're using.
No it's not. This is a not a good way to ask a question on the internet.
And it's really impossible to give you a direction what to do if you don't post the code throwing the exception and tell us where the exception comes from.

NHibernate "illegal access to loading collection" error

What is the reason of this error? My class is Course and it has notes. Mapping is as below. Any idea?
<bag name="Notes" table="NOTE" cascade="all">
<key column="COURSEID"/>
<one-to-many class="Server.Data.Note, Server.Data"/>
</bag>
<bag name="Notes" table="NOTE" cascade="all" inverse="true">
<key column="COURSEID"/>
<one-to-many class="Server.Data.Note, Server.Data"/>
</bag>
inverse="true" solves my problem :)
I my case the reason was that I was mapping a list to an abstract type (during a refactoring). When I changed the class from being abstract, it worked.
In my case the reason was that I converted an int to an enum (public enum FieldType : int { }).
Somehow, that convertion made an error jump where a Field had no Question. I made Question_id not nullable directly in the db, and removed the Fields with null question_id... and the error disappeared. (Replaced by another one, Can't parse 32 as int.. But still, improvement. I think the db type needs to be different.)
"Any sufficiently advanced technology is indistinguishable from magic."

nHibernate mapping generic IDictionary

I've asked this elsewhere and not got any sensible reply
I'm trying to map an IDictionary. I have this mapping:
<class name="MyProject.Item, MyProject" table="Item">
<...>
<map name="Properties" access="property" table="ItemProperties" lazy="false">
<key column="ItemID" />
<index column="Idx" type="int" />
<element column="Value" type="System.Boolean, mscorlib"/>
</map>
I can persist data, but when the data is retrieved I get an nHibernate exception:
{"The value "0" is not of type "Project.PropertyType" and cannot be used in this generic collection. Parameter name: key"}
So it can't map to the enum, but why ? if I have a regular property that uses an enum, it works fine.
Is what I'm trying to do even possible ? I can't find much info on doing this.
Your mapping shows the key as an integer, not as an enum. To map the enum properly, use type="MyProject.Project.PropertyType, MyProject".
However, normally for an enum the best approach is to leave the type information out of the mapping file altogether and let NHib pick it up through reflection. My reading of the NHib source implies that if you are mapping into a generic IDictionary<K,V> then NHib should pick up the exact type of your key via reflection. IOW you still should be able to leave out the type attribute.