AliasToBean DTO with known type - nhibernate

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

Related

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.

Automatically update Entity instance from class MVC 3

I've got a class that closely resembles one of my entities (I use the class for JSON de/serialization because the entity fails conversion to JSON, one of the known gotchyas of JSON + MVC).
Once I deserilize a JSON string into my object, is there a way to automatically update the associated Entity model instance. The property names are the same.
e.g.
'myDeserialized is the deserialized JSON object coming over the wire
Dim entityInstance As DLL.Person = db.getPersonById(myDeserialized.id)
myDeserialized.update(entityInstance)
Where this just goes through and takes all the properties in myDeserialized and updates the same named property in entityInstance?
Or is it possible to just iterate over a key-value pair of all the properties in an object/entity?
I'm looking for something like TryUpdateModel(), but that only works with forms, right? I don't want to tie my data to a form, that's all.
Thanks!
I don't know what type and version of EF you use, but there are very powerful functions for iterating on the entities properties. Which mean you can easily make your update function on the entity or its baseclass' partial (entityInstance.Update(myDesrialized)).
If you use EntityObject, then you can get an ObjectStateEntry for your entities and via this class you can very easily achieve this.
Please let us know what version and type of EF you use (POCO?)

CF9 ORM Populating an entity with an object

I am using Model-Glue/Coldspring for a new application and I thought I would throw CF9 ORM into the mix.
The only issue I am having right now is with populating an entity with an object. More or less the code below verifies that only one username can exist. There is some other logic that is not displayed.
My first thought was to using something like this:
var entity = entityload('UserAccount' ,{UserName=arguments.UserAccount.getUserName()},"true")
entity = arguments.UserAccount;
How ever this does not work the way that I expected. Is it even possible to populate an entity with an object or do I need to use the setters?
Not sure if this is what you're looking for. If you have...
component persistent="true" entityName="Foo"
{
property a;
property b;
}
You can pass a struct in the 2nd param to init the entity (added in CF9.0.1 I believe)
EntityNew("Foo", {a="1",b="2"});
To populate Foo with another object, you can use the Memento pattern, and implement a GetMemento() function to your object that returns a struct of all its properties.
EntityNew("Foo", bar.getMemento());
However, CF does NOT call your custom setters! If you want to set them using setters, you may add calls to the setters in your init() constructor, or use your MVC framework of choice to populate the bean. In Model-Glue, it is makeEventBean().
Update: Or... Here's hack...
EntityNew("Foo", DeserializeJSON(SerializeJSON(valueObject)));
Use this at your own risk. JSON might do weird things to your numbers and the 'yes','no','true','false' strings. :)
Is it even possible to populate an entity with an object or do I need to use the setters?
If you mean "Is it possible to create load an ORM Entity from an instance of that persistent CFC that already exists and has properties set?", then yes you can using EntityLoadByExample( object,[unique] )
entity = EntityLoadByExample( arguments.userAccount,true );
This assumes the userAccount CFC has been defined as persistent, and its username value has been set before being passed in (which seems to be the case in your situation).
Bear in mind that if any other properties have been set in the object you are passing, including empty strings, they will be used as filters to load the entity, so if they do not exactly match a record in your database, nothing will be loaded.

NHibernate Component mapping (Creating Criteria)

Is there any way to create an “alias” for a component?
I have a “Criteria Builder” that takes strings in the format of “Address.City” (or “User.Address.City”, …) and creates an ICriteria (filters and sorts) based on it.
I am using components to map the “Address” class so it stays in the same table as “User”.
The exception I am getting is:
NHibernate.QueryExceptioncould not resolve property: City of: MyNamespace.User
If I attempt to do not create an “alias” for the Address Component, it works just fine.
However, as it is a criteria builder, is there a way to detect that “Address” is a component and avoid the call criteria.CreateAlias(“Address”)? Any work around?
This is the same question as mine, however the solution is not viable to me (I do not create criteria manually for each query).
Any help would be much appreciated!
You can't create an Alias for Address because Address is not a mapped entity. The only difference between CreateAlias and CreateCriteria is that the former returns the original Criteria, whereas the latter returns the new Subcriteria. So the only classes you can create Criteria for are classes that have been mapped. Since components are not mapped classes, you can't create a criteria around them.
The only suggestion I have is to have your Address class either to implement an empty descriptor interface like IComponent or mark it with a custom ComponentAttribute. Then your CriteriaBuilder can check whether or not the class it's creating a criteria for has this meta data and ignore it.

Specifying properties to be updated in linq query

I want to be able to specify the properties to get populated/updated in the linq expression.
Something in the following fashion:
Proxy.UpdateEmployee(List<string> propertiesNames)
Proxy.GetEmployee() //inside the method populate only certain properties
The return values must be of known type(no anonymous types accepted).
DLINQ enable to select by specifying properties' names but the result is IQueryable interface and I'm unable to AsEnumerable() it in order to build the known type query afterwards.
You have to use reflection to modify instance properties by name.
So wherever you're updating your object with LINQ you need to do something like this:
foreach (string propName in propertiesNames)
{
PropertyInfo prop = this.GetType().GetProperty(propName);
prop.SetValue(valueForProp);
}