NHibernate sub-collection using QueryOver - nhibernate

I have simple classes:
public class Order
{
public int Id {get;set;}
public IList<Name> Names{get;set;}
}
public class Name
{
public int Id {get;set;}
public int LangId {get;set;}
public string LocalName {get;set;}
}
The quesetion is how to query subcollection of Order to get all that have some Order.Names.LocalName (something like this):
IList<Order> orders = repository.GetByProductLocalName("laptop");
I would like to use new NH3 feature QueryOver, not using Linq (I'v found some solutions in SO but all of them uses Linq).

All you need to do is declare an alias variable for the Names collection and then you can use that in the where clause...
String localName = "laptop";
Name namesAlias = null;
return session.QueryOver<Order>()
.JoinAlias(x => x.Names, () => namesAlias)
.Where(() => namesAlias.LocalName == localName)
.TransformUsing(Transformers.DistinctRootEntity)
.List<Order>();

Related

NHibernate join 2 tables and project to DTO with collection

I am trying to join 2 tables, and project directly to DTOs (NHibernate 5).
I have following entities:
public class Person {
public Guid Id {get;set;}
public string Name {get;set;}
}
public class Car {
public Guid Id {get;set;}
public string Brand {get;set;}
public Person Owner {get;set;}
}
as we see, there is just reference from Car to Person (car knows its owner), and this is ok in my whole project.
However, there is one place, where I need to query all Persons, and make each person with collection of owned cars.
I created such DTOs:
public class PersonDto {
public Guid Id {get;set;}
public string Name {get;set;}
public IList<CarDto> {get;set;}
}
public class CarDto {
public Guid Id {get;set;}
public string Brand {get;set;}
}
it is kind of present the data linked together upside-down.
This task seems trivial using SQL or LINQ (GroupJoin) however I found it extremly hard to do in NH, since GroupJoin is not implemented in NH.
Can you please help me how to solve above issue?
Just add a Car collection to the existing Person entity and mark the collection inverse. Collections in NHibernate are lazy by default, so when you query Person, it won't read the cars from the DB, until you start iterating them. In other words adding the Car collection won't affect the way your code works.
When you want to efficiently query persons together with cars, force NH to do a join
.QueryOver<Person>.Fetch(person => person.Cars).Eager
I'd like to answer my own question. Thanks Rafal Rutkowski for his input.
To get data that has association in only 1 direction, we need to introduce a new data model, and then, manually convert result to our entities. I hope following example is best possible answer:
1) create such data model to store NH response:
private class PersonCarModelDto
{
public Guid PersonId { get; set; }
public string PersonName { get; set; }
public Guid CarId { get; set; }
public string CarBrand { get; set; }
}
2) create such a model to store hierarchical data as output:
private class PersonModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public IList<CarModel> Cars { get; set; }
}
private class CarModel
{
public Guid Id { get; set; }
public string Brand { get; set; }
}
3) now the NH query:
Person personAlias = null;
Car carAlias = null;
PersonCarModelDto resultAlias = null;
var response = GetCurrentSession().QueryOver<Car>(() => carAlias) // notice we are going from from 'downside' entity to 'up'
.Right.JoinAlias(c => c.Owner, () => personAlias) // notice Right join here, to have also Persons without any car
.SelectList(list => list
.Select(() => personAlias.Id).WithAlias(() => resultAlias.PersonId)
.Select(() => personAlias.Name).WithAlias(() => resultAlias.PersonName)
.Select(() => carAlias.Id).WithAlias(() => resultAlias.CarId)
.Select(() => carAlias.Brand).WithAlias(() => resultAlias.CarBrand)
.TransformUsing(Transformers.AliasToBean<PersonCarModelDto>())
.List<PersonCarModelDto>()
;
4) now we have flat data as a list of PersonCarModelDto, but we want to make output model:
var modelResult = response.GroupBy(p => p.PersonId)
.Select(x => new PersonModel
{
Id = x.Key,
Name = x.Select(y => y.PersonName).First(), // First() because each PersonName in that group is the same
Cars = x.Select(y => new CarModel
{
Id = y.CarId,
Name = y.CarBrand
})
.ToList()
})
.ToList()
;
Conclusions:
the problem is much easier to solve having bidirectional associations
if for some reason, you don't want bidirectional associations, use this technique
this approach is also useful if your entities has a lot of other properties, but for some reason you need just a small part of them
(optimiziation of data returned for DB)

NHibernate Linq Startwith generates outer join

I have two entities that are connected through one to many relationship.
like this example:
public class Category
{
public int Id {get; set; }
public string Name {get; set;}
}
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
public Category ProductCategory {get; set;}
}
and the mapping using fluent nhibernate
public class CategoryMap : ClassMap<Category>
{
....
}
public Class ProductMap: ClassMap<Product>
{
...
References(x => x.ProductCategory).Column("CategoryId");
}
When I do search using linq to NHibernate with where clause and equal, it generates inner join between product and category
so this
var query = session.Query<Product>()
.Where (x => x.ProductCategory.Name == "abc");
this will generate inner join
but when I do search with startwith like this
var query = session.Query<Product>()
.Where (x => x.ProductCategory.Name.StartWith("abc"));
this will generate outer join between the two.
Why, and how can I force to generate inner join?
You can do it using QueryOver, which is another method to create query in NHibernate. In that case, you specify the join type as you want.
Category category = null;
var result = session.QueryOver<Product>()
.JoinAlias(x => x.ProductCategory, () => category, JoinType.InnerJoin)
.Where(Restrictions.Like(Projections.Property(() => category.Name), "abc%", MatchMode.Start))
.List();
On the other hand, query over is more verbose code, you have to specify a lot of things you avoid using linq.

Not sure how to join tables using Fluent NHibernate

I'm using NHibernate on legacy tables and after looking through our codebase, I seem to be the only person with this need. I need to join two tables so I can run a query, but I haven't made any progress today. I'll try to abbreviate where it makes sense in my code snippets. Care to help?
Tables--
Order
OrderID (primary key)
OrderName
OrderType
OrderLocation
OrderAppendix
ID (composite key)
Key (composite key)
Value (composite key)
The ID portion of the OrderAppendix composite key is associated with OrderID in the Order table; therefore, and Order can have several entries in the OrderAppendix table.
Domain Objects--
[Serializable]
public class Order
{
public virtual string OrderID { get; set; }
...
public virtual string OrderLocation { get; set; }
}
[Serializable]
public class OrderAppendix
{
public virtual string ID { get; set; }
public virtual string Key { get; set; }
public virtual string Value { get; set; }
public override bool Equals(object obj)
{
...
}
public override int GetHashCode()
{
...
}
}
Mapping
internal sealed class OrderMap : ClassMap<Order>
{
Table("Order");
Id(x => x.OrderID).Column("OrderID").Length(20).GeneratedBy.Assigned();
Map( x => x.OrderName).Column("OrderName")
....
}
internal sealed class OrderAppendixMap : ClassMap<OrderAppendix>
{
Table("OrderAppendix");
CompositeId()
.KeyProperty(x => x.ID, "ID")
....
Map( x => x.ID).Column("ID);
...
}
I won't muddy this up with my futile attempts at joining these tables, but what I would like to do is query by things like OrderType or OrderLocation given that the results all have the same Value from the OrderAppendix table.
Example desired SQL
SELECT * FROM ORDER
INNER JOIN
ON Order.OrderID = OrderAppendix.ID
WHERE OrderAppendix.Key = "Stuff"
Edit
Here's where I've gotten by reading the documentation on "QueryOver"
http://nhibernate.info/doc/nh/en/index.html#queryqueryover
Order Order = null;
OrderAppendix OrderAppendix = null;
resultList = session.QueryOver<Order>(() => Order)
.JoinAlias(() => Order.OrderAppendix, () => OrderAppendix)
.Where(() => OrderAppendix.Key == "MatchThis")
.List();
I think I'm on the right track using aliases to join the table, but obviously I haven't found a way to inform NHibernate of the many-to-one mapping that's needed. Also, you can see that I've added a property of type OrderAppendix to Order in order to the use the alias functionality.
Well, I didn't get why you did not used standard parent-child approach using HasMany on Order side and Reference of Appendix. This is because of composite key on appendix side?
If you would do that, you will be able to provide following HQL:
SELECT o FROM Order o
LEFT JOIN FETCH o.apxs a
WHERE a.Key="Stuff"

QueryOver child collection from parent

I have this 2 objects:
public class Parent
{
public virtual int Poid { get; set; }
public virtual IEnumerable<Child> Child { get; set; }
}
public class Child
{
public virtual int Poid { get; set; }
public virtual string Name {get; set;}
}
I want to use NHibernet QueryOver API to get a child based on the Parent Id and Child Id, That's mean something like give me the child with Id = x belonging to the parent with Id = y.
I tried something like this:
return Session.QueryOver<Parent>().Where(p => p.Poid == y)
.JoinQueryOver(p => p.WishesLists)
.Where(c => c.Poid == x)
.SingleOrDefault<Child>();
But I'm getting an exception that is not possible to convert an object of type Child to Parent.
How is the correct form to QueryOver starting with a Parent Entity but return a Child Entity?
I don't know if this is possible with QueryOver, I worked at it for a while without getting anywhere. It is possible with LINQ:
var child = session.Query<Parent>()
.Where(p => p.Poid == y)
.SelectMany(p => p.WishesLists)
.SingleOrDefault(c => c.Poid == x);
I strongly prefer the LINQ syntax over QueryOver.
See also NH-3176

Nhibernate projection with child collection

Using NHibernate 2.1, I'm trying to project an entity and its child collection into a DTO. My entity looks like this..
public class Application
{
public int Id {get;set;}
public string Name {get;set;}
public List<ApplicationSetting> Settings {get;set;}
// A bunch of other properties that I don't want in the DTO
}
public class ApplicationSetting
{
public int Id {get;set;}
public string Name {get;set;}
public string Code {get;set;}
// A bunch of other properties that I don't want in the DTO
}
My DTO looks like this..
public ApplicationDto
{
public int Id {get;set;}
public string Name {get;set;}
public List<ApplicationSettingDto> Settings {get;set;}
}
public class ApplicationSettingDto
{
public int Id {get;set;}
public string Name {get;set;}
public string Code {get;set;}
}
My code to select JUST the Application and project it is this (using Nhibernate 2.1 and nhLambdaExtensions)
var applicationAlias = new Application();
var criteria = Session
.Add<Application>(a => a.Id == id);
int? Id = null;
string Name = null;
criteria
.SetProjection
(
Projections.Distinct(
Projections.ProjectionList()
.Add(LambdaProjection.Property<Application>(a => a.Id).As(() => Id))
.Add(LambdaProjection.Property<Application>(a => a.Name).As(() => Name))
)
);
criteria.SetResultTransformer(Transformers.AliasToBean(typeof(ApplicationDto)));
var contract = criteria.UniqueResult<ApplicationDto>();
My question is, how do I project just SOME of the properties from the ApplicationSettings entity to the ApplicationSettingsDto child collection?
I think you might need to do a MutiQuery and bring together the DTO parents and children yourself.