NHibernate criteria fetchmode - nhibernate

I have a type Type1 with a property Type2s consisting of a List<Type2>. I have configured the NHibernate mapping for the property as follows:
[Map(0, Table = "Type2s", Schema = "MySchema", Cascade = CascadeStyle.All, Lazy = true, Inverse = true)]
[Key(1, Column = "Type1Id")]
[OneToMany(2, Class = "Type2, MyNamespace")]
What is the difference in behavior between these two criteria for retrieval of Type1 instances:
var criteria1 = DetachedCriteria.For<MyType1>();
var criteria2 = DetachedCriteria.For<MyType1>().SetFetchMode("Type2s", FetchMode.Join);
When I invoke .List on the executable criteria from these criteria, presumably the SQL to retrieve the Type2s associated with each Type1 instance is not run until I actually attempt to access the property because the property is marked as being Lazy. Is this a correct assumption?
If I want to force evaluation of the Lazy property how can this best be achieved?

I'm not very familiar with attribute binding vs. hbm/fluent, but I believe you have solved your own problem!
You are correct assuming that the data for the Type2s will not be loaded until request because of the bag being lazy. Your second criteria's fetchmode forces those object to be hydrated at the same time, ie. in one database roundtrip.
As an aside, FetchMode.Join is equivalent to FetchMode.Eager (which is a better name re:laziness in my opinion).
article explaining it a little more in depth:
http://davidhayden.com/blog/dave/archive/2008/12/06/ImprovingNHibernatePerformanceFetchingStrategiesFetchModeFluentNHibernate.aspx
describing FetchMode.Join and FetchMode.Eager:
http://bchavez.bitarmory.com/archive/2008/04/04/differences-between-nhibernate-fetchmode.eager-and-fetchmode.join.aspx

Related

How to update two columns with same name from two tables in a join query

I am getting an error:
Property or Indexer cannot be assigned to "--" it is read only
when trying to update two columns with the same name in two tables in a join query. How do I get this to work? Thanks!
The anonymous object created in your projection ("select new" part) is read-only and its properties are not tracked by data context by any means.
Instead, you can try this:
//...
select new
{
p1 = p,
p2 = t
}
foreach (var row in updates)
{
row.p1.Processed = true;
row.p2.Processed = true;
}
In order to improve performance you may also want to take a look at batch update capabilities of Entity Framework Extensions (if you are using Entity Framework): https://entityframework-extensions.net/overview
Yes, that's due to anonymous type properties are read only, from documentation:
Anonymous types provide a convenient way to encapsulate a set of
read-only properties into a single object without having to explicitly
define a type first.
I suggest you to create a custom class with the two entities you need (a DTO):
public class PassengerDTO
{
public Passenger Passenger {get;set}
public PassengerItinerary PassengerItinerary {get;set}
}
And use it in your projection, You need the entity instances and not just the properties you want to modify because, when you modify the Processed property in the foreach the proxy class that represent your entity is going to change the status of you entity to Updated.

AliasToBean DTO with known type

All the examples I am finding for using the AliasToBean transformer use the sessions CreateSqlQuery method rather than the CreateQuery method. They also only return the basic value types, and not any object's of the existing mapped types.
I was hoping it would be possible that my DTO have a property of one of my mapped Domain objects, like below, but I am not getting traction. I get the following exception:
Could not find a setter for property '0' in class 'namespace.DtoClass'
My select looks like the following on my mapped classes (I have confirmed the mappings pull correctly):
SELECT
fcs.MeasurementPoint,
fcs.Form,
fcs.MeasurementPoint.IsUnscheduled as ""IsVisitUnscheduled"",
fcs.MultipleEntryAllowed
FROM FormCollectionSchedule fcs
My end query will be more complex, but I wanted to confirm if this AliasToBean method can return mapped domain objects as well as basic field values from tables retrieved via sql.
the query execution looks like the following:
var result = session.CreateQuery(hqlQuery.ToString())
.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof (VisitFormCollectionResult)))
.List<VisitFormCollectionResult>();
note: the VisitFormCollectionResult DTO has more properties, but I wanted to know if I could populate the domain object properties matching the names
update found my problem! I have to explicitly alias each of the fields. once I added an alias, even though the member property on the class matched my DTO's property name, the hydration of the object worked correctly.
The answer to my own question was that each of the individual fields in the select needed an explicit alias matching the property, regardless if the field name already matched the property name of the DTO object:
SELECT
fcs.MeasurementPoint as "MeasurementPoint",
fcs.Form as "Form",
fcs.MeasurementPoint.IsUnscheduled as "IsVisitUnscheduled",
fcs.MultipleEntryAllowed as "MultipleEntryAllowed"
FROM FormCollectionSchedule fcs

WCF DataServiceQuery for derived type

I have a base entity, and a derived entity, with an extra boolean property. My WCF Data Service exposes an EntitySet of the base entity. I can query it in a browser:
http://myserver/myservice/BaseSet/Namespace.Derived()?$filter=(BoolProp eq false)
And I get a collection of objects of my Derived type. All good.
In my client I have a grid which takes a DataServiceQuery. So I constructed my query:
var query = context.CreateQuery<Proxy.Derived>("BaseSet");
But when I try to filter on derived properties it returns an error. And when I examined the URL it used in its request it's missing the chunk for my derived type, i.e. it looked like:
http://myserver/myservice/BaseSet()?filter=(BoolProp eq false)
What's the proper way to construct a DataServiceQuery that I can use to query using properties on my derived type?
Turns out all I needed was to extend the entitySetName argument to include my derived type:
var query = context.CreateQuery<Proxy.Derived>("BaseSet/Namespace.Derived")();
The name of the argument isn't great. Now I actually bother to read the documentation it does tell me that the entitySetName should be "A string that resolves to a URI." Not sure that helps most people but I should have checked it sooner.

NHibernate: why field.camelcase?

Can someone tell me why in NHibernate mapping we can set access="field.camelcase", since we have access="field" and access="property"?
EDIT: my question is "why we can do this", not "what does it mean". I think this can be source of error for developper.
I guess you wonder what use field.camelcase have when we can do the same with just field? That's true, but that would give (NH) properties unintuive names when eg writing queries or reference the property from other mappings.
Let's say you have something you want to map using the field, eg
private string _name;
public string Name { get { return _name; } }
You sure can map the field using "field" but then you would have to write "_name" when eg writing HQL queries.
select a from Foo a where a._name = ...
If you instead using field.camelcase the data, the same query would look like
select a from Foo a where a.Name...
EDIT
I now saw you wrote "field.camelcase" but my answer is about "field.camelcase-underscore". The principles are the same and I guess you get the point ;)
the portion after the '.' is the so called naming strategy, that you should specify when the name you write in the hbm differ from the backing field. In the case of field.camelcase you are allowed to write CustomerName in the hbm, and NHibernate would look for a field with name customerName in the class. The reason for that is NHibernate not forcing you to choose a name convention to be compliant, NH will works with almost any naming convention.
There are cases where the properties are not suitable for NH to set values.
They may
have no setter at all
call validation on the data that is set, which is not used when loading from the database
do some other stuff that is only used when the value is changed by the business logic (eg. set other properties)
convert the value in some way, which would cause NH performing unnecessary updates.
Then you don't want NH to call the property setter. Instead of mapping the field, you still map the property, but tell NH to use the field when reading / writing the value. Roger has a good explanation why mapping the property is a good thing.

NHibernate: lazy loaded properties?

NHibernate question:
Say I have a SQL table Person and it has a Picture column ( OLE Object ) . I have a class Person and it has : byte[] Picture attribute.
Is it possible to map like this ?
<property name = "Picture" column = "Picture" type = "System.Byte[]" lazy="true" />
Does the "lazy" keyword have any effect on properties or can it only be used when working with collections / bags etc?
It appears that this feature just landed in the NHibernate trunk:
http://ayende.com/Blog/archive/2010/01/27/nhibernate-new-feature-lazy-properties.aspx
I have not found any way to get this to work, but the following two ways may help you around the problem you imply:
You can map two classes for the same table, one including the byte array, the other not.
You can include a many-to-one property mapping to the same table, where the child class has the byte array included, and you then access the binary using Person.PersonPicture.Picture rather than just Person.Picture; the intermediate class can now be lazy loaded.
Neither is ideal, but they do work. Short answer - collections and many-to-one properties can be lazy loaded, straight properties not.