Why does NHibernate's LINQ provider generate invalid T-SQL for a GroupBy()? - nhibernate

I'm trying to do what seems like a simple query for the number of Products produced by each Manufacturer, but NHibernate isn't generating T-SQL that MS SQL Server finds valid.
session.Query<Product>()
.GroupBy(p => p.Manufacturer)
.Select(grp => new {Mftr = grp.Key.Name, ProductCount = grp.Count()})
.ToList();
This seems dead simple, but the SQL statement that NHibernate generates doesn't include all the necessary column names, so it fails when running against a SQL Server 2008 or SQL Server CE database. If I point the same code to an in-memory SQLite database, it works fine.
More information is below, and I also created a small console application that demonstrates my problem. How do I fix this problem?
Generated SQL
select manufactur1_.Id,
cast(count(*) as INT),
manufactur1_.Id,
manufactur1_.Name
from "Product" product0_
left outer join "Manufacturer" manufactur1_
on product0_.Manufacturer_id=manufactur1_.Id
group by manufactur1_.Id -- Where's manufactur1_.Name?
Entities
public class Product {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
}
public class Manufacturer {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
FNH Mappings
public class ProductMap : ClassMap<Product> {
public ProductMap() {
Id(x => x.Id).GeneratedBy.HiLo("1");
Map(x => x.Name);
References(x => x.Manufacturer).Cascade.SaveUpdate().Not.Nullable();
}
}
public class ManufacturerMap : ClassMap<Manufacturer> {
public ManufacturerMap() {
Id(x => x.Id) .GeneratedBy.HiLo("1");
Map(x => x.Name);
}
}

Here's a QueryOver version...
//alias variables
Manufacturer m = null;
ManufacturerProducts dto = null;
var result = Session.QueryOver<Product>
.Left.JoinAlias(x => x.Manufacturer, () => m)
.SelectList(list => list
.SelectGroup(() => m.Id).WithAlias(() => dto.Id)
.SelectGroup(() => m.Name).WithAlias(() => dto.Name)
.SelectCount(x => x.Id).WithAlias(() => dto.ProductCount))
.TransformUsing(Transformers.AliasToBean<ManufacturerProducts>())
.List<ManufacturerProducts>();

Related

Hierarchical entity parent key in NHibernate ByCode

Using NHibernate 3.2 ByCode configuration, I am attempting to map the following hierarchical entity:
public class BusinessType
{
public virtual Guid BusinessTypeId { get; set; }
public virtual Guid? ParentBusinessTypeId { get; set; }
public virtual String BusinessTypeName { get; set; }
public virtual ICollection<BusinessType> Children { get; set; }
}
with this ClassMapping:
public class BusinessTypeMapper : ClassMapping<BusinessType>
{
public BusinessTypeMapper()
{
Id(x => x.BusinessTypeId, x => x.Type(new GuidType()));
Property(x => x.ParentBusinessTypeId, x => x.Type(new GuidType()));
Property(x => x.BusinessTypeName);
Set(x => x.Children,
cm =>
{
// This works, but there is an ugly string in here
cm.Key(y => y.Column("ParentBusinessTypeId"));
cm.Inverse(true);
cm.OrderBy(bt => bt.BusinessTypeName);
cm.Lazy(CollectionLazy.NoLazy);
},
m => m.OneToMany());
}
}
This works fine, but I'd rather be able to specify the key of the relation using a lambda so that refactoring works. This seems to be available, as follows:
public class BusinessTypeMapper : ClassMapping<BusinessType>
{
public BusinessTypeMapper()
{
Id(x => x.BusinessTypeId, x => x.Type(new GuidType()));
Property(x => x.ParentBusinessTypeId, x => x.Type(new GuidType()));
Property(x => x.BusinessTypeName);
Set(x => x.Children,
cm =>
{
// This compiles and runs, but generates some other column
cm.Key(y => y.PropertyRef(bt => bt.ParentBusinessTypeId));
cm.Inverse(true);
cm.OrderBy(bt => bt.BusinessTypeName);
cm.Lazy(CollectionLazy.NoLazy);
},
m => m.OneToMany());
}
}
The problem is that this causes NHibernate to generate a column called businesstype_key, ignoring the already-configured ParentBusinessTypeId. Is there any way to make NHibernate use a lambda to specify the relation, rather than a string?
I never need to navigate from children to parents, only from parents
to children, so I hadn't thought it necessary
then remove public virtual Guid? ParentBusinessTypeId { get; set; } completly. NH will then only create "businesstype_key" (convention) and no "ParentBusinessTypeId". if you want to change that then you have to specify your prefered columnname with cm.Key(y => y.Column("yourpreferredColumnName"));

OneToOne mapping by code nhibernate 3.2

I'm trying to upgrade a project and use the build in code mapper.
I have 2 entities:
public class Person {
public virtual int Id { get; set; }
public virtual User User { get; set; }
}
public class User {
public virtual int Id { get; set; }
public virtual User Person { get; set; }
}
The database structure is like this:
table: users, fields: id
table: people, fields: id, userId
With FluentNHibernate i could map it like this:
public class UserMap : ClassMap<User> {
public UserMap() {
Id(x => x.Id).GeneratedBy.Identity();
HasOne(x => x.Person).PropertyRef("User").Not.LazyLoad();
}
}
public class PersonMap : ClassMap<Person> {
public PersonMap() {
Id(x => x.Id).GeneratedBy.Identity();
References(x => x.User).Column("UserId").Not.Nullable().Not.LazyLoad();
}
}
But is can't get it working with NH 3.2 build in code mapper.
This is what i have done so far.
OneToOne(x=>x.Person, m => {
m.PropertyReference(typeof(Person).GetProperty("User"));
});
OneToOne(x=>x.User, m => {});
Now the relation is mapped on User.Id and Person.Id but personid and userid can be different.
It's also possible that a user has no person.
from Users user0_ left outer join People person1_ on user0_.Id=person1_.Id
I think i have to specify that Person -> User is mapped with the UserId column but how?.
Since you were using References() in Fluent, you need to convert that to ManyToOne():
public class UserMap : ClassMapping<User>
{
public UserMap()
{
Id(x => x.Id, x => x.Generator(Generators.Identity));
OneToOne(x => x.Person,
x => x.PropertyReference(typeof(Person).GetProperty("User")));
}
}
public class PersonMap : ClassMapping<Person>
{
public PersonMap()
{
Id(x => x.Id, x => x.Generator(Generators.Identity));
ManyToOne(x => x.User,
x => x => { x.Column("UserId"); x.NotNullable(true); });
}
}
Two notes:
The type of User.Person should be Person, not user (that's probably just a bad edit)
.Not.LazyLoad() is almost always a bad idea. See NHibernate is lazy, just live with it

FluentNHibernate: Nested component mapping results in NHiberate QueryException

Hi i have a problem with mapping in Nhibernate. When I run a linq query referring to one of the component classes of my entity, I get a QueryException as below:
could not resolve property: ClosedCases of: Project.Entities.Headline
I have one table with records which i want to map into multiple objects of my headline entity.
Question:
Is there something wrongly set up in my mapping?
My Headline entity is separated into multiple logical classes as you can see below
public class Headline:Entity
{
public virtual DateTime Date { get; set; }
public virtual TeamTarget Teamtarget { get; set; }
}
public class TeamTarget : Entity
{
public virtual DateTime FromDate { get; set; }
public virtual DateTime ToDate { get; set; }
public virtual TargetItem AchievedTarget { get; set; }
public virtual Team Team { get; set; }
}
public class TargetItem : Entity
{
public virtual decimal ClosedCases { get; set; }
public virtual decimal Invoicing { get; set; }
}
Mapping file:
public class HeadlineMap: ClassMap<Headline>
{
public HeadlineMap()
{
Table("Headlines.Headlines");
Id(x => x.Id).Column("HeadlinesId");
Map(x => x.Date);
Component(x => x.Teamtarget, t =>
{
t.References(x => x.Team).Column("TeamId").Cascade.None();
t.Component(x => x.AchievedTarget, ti =>
{
ti.Map(x => x.Invoicing).Column("TeamInvoicing");
ti.Map(x => x.ClosedCases).Column("TeamClosedCases");
});
});
The Linq query I am running looks like this:
decimal closedCases = _headlineRepository.All
.Where(x =>
x.Date >= DateTimeExtensionMethods.FirstDayOfMonthFromDateTime(selectMonthFromDate)
&& x.Date <= DateTimeExtensionMethods.LastDayOfMonthFromDateTime(selectMonthFromDate)
&& x.Teamtarget.Team.Id == teamId
).Average(x => x.Teamtarget.AchievedTarget.ClosedCases);
I know that i can access headline item by using team entity by team id and this works, just have problem with the mapping of achieved target.
any ideas?
I think your mapping is fine. But as far as I know, it isn't possible to query a nested component with Linq to NHibernate. It can't understand what joins to do, it becomes too complex.
I think it is possible using NHibernate 3's QueryOver API using JoinQueryOver or JoinAlias. You should read this: QueryOver in NH 3.0
Maybe something like this would work:
Headline headlineAlias = null;
TeamTarget targetAlias = null;
Team teamAlias = null;
TargetItem targetItemAlias = null;
var query = session.QueryOver<Headline>(() => headlineAlias)
.JoinAlias(() => headlineAlias.Teamtarget, () => targetAlias)
.JoinAlias(() => targetAlias.Team, () => teamAlias)
.JoinAlias(() => targetAlias.AchievedTarget, () => targetItemAlias)
.Where(x => x.Date >= DateTimeExtensionMethods.FirstDayOfMonthFromDateTime(selectMonthFromDate) && x.Date <= DateTimeExtensionMethods.LastDayOfMonthFromDateTime(selectMonthFromDate))
.And(() => teamAlias.Id == teamId)
.Select(Projections.Avg(() => targetItemAlias.ClosedCases))
.SingleOrDefault<decimal>();

Getting records back from many to many fluent nhibernate?

I made a many to many relationship by following the fluent nhibernate Getting started tutorial .
(source: fluentnhibernate.org)
Now I am not sure how to retrieve data. For instance what happens if I want to get all the products a store carries.
So I would need to use the storeId on the products table. Yet there is no storeId in the products table and I don't have a class that actually contains mapping or properties for StoreProduct.
So I can't go
session.Query<StoreProduct>().Where(x => x.StoreId == "1").toList();
So do I need to do a join on Store and Products and then do a query on them?
Edit
Here is a watered down version of what I have.
public class Student
{
public virtual Guid StudentId { get; private set; }
public virtual IList<Course> Courses { get; set; }
public virtual IList<Permission> Permissions{get; set;}
public Student()
{
Courses = new List<Course>();
Permissions = new List<Permission>();
}
public class StudentMap : ClassMap<Student>
{
public StudentMap()
{
Table("Students");
Id(x => x.StudentId).Column("StudentId");
HasManyToMany(x => x.Permissions).Table("PermissionLevel");
HasManyToMany(x => x.Courses).Table("PermissionLevel");
}
}
public class CourseMap : ClassMap<Course>
{
public CourseMap()
{
Table("Courses");
Id(x => x.CourseId).Column("CourseId");
HasManyToMany(x => x.Permissions ).Table("PermissionLevel");
HasManyToMany(x => x.Students).Table("PermissionLevel");
}
}
public class Course
{
public virtual int CourseId { get; private set; }
public virtual IList<Permission> Permissions { get; set; }
public virtual IList<Student> Students { get; set; }
public Course()
{
Permissions = new List<Permission>();
Students = new List<Student>();
}
}
public class PermissionMap : ClassMap<Permission>
{
public PermissionMap()
{
Table("Permissions");
Id(x => x.PermissionId).Column("PermissionId");
HasManyToMany(x => x.Students).Table("PermissionLevel");
}
}
public class Permission
{
public virtual int PermissionId { get; private set; }
public virtual IList<Student> Students {get; set;}
public Permission()
{
Students = new List<Student>();
}
}
var a = session.Query<Student>().Where(x => x.Email == email).FirstOrDefault();
var b = session.Get<Student>(a.StudentId).Courses;
error what I get when I look into b.
could not initialize a collection:
[Student.Courses#757f27a2-e997-44f8-b2c2-6c0fd6ee2c2f][SQL:
SELECT courses0_.Student_id as
Student3_1_, courses0_.Course_id as
Course1_1_, course1_.CourseId as
CourseId2_0_, course1_.Prefix as
Prefix2_0_, course1_.BackgroundColor
as Backgrou3_2_0_ FROM PermissionLevel
courses0_ left outer join Courses
course1_ on
courses0_.Course_id=course1_.CourseId
WHERE courses0_.Student_id=?]"
No, you don't. StoreProduct is special table that hold many-to-many relations between Store and Products. NHibernate able to populate Store's collection of products using this table automatically. It should be described in mapping. You should query just like this:
var storeProducts = session.Get<Store>(1).Products;
Here's mapping for Store:
public class StoreMap : ClassMap<Store>
{
public StoreMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Staff)
.Inverse()
.Cascade.All();
HasManyToMany(x => x.Products)
.Cascade.All()
.Table("StoreProduct");
}
}
Notice line HasManyToMany(x => x.Products) and .Table("StoreProduct") they tell NHibernate to use table StoreProduct as source for many-to-many relation store objects in collection Products.
You have wrong mappings for Student:
HasManyToMany(x => x.Permissions).Table("PermissionLevel");
HasManyToMany(x => x.Courses).Table("PermissionLevel");
It should be following:
HasManyToMany(x => x.Courses).Table("StudentCourses");
And you Student class is incomplete.

Map One-To-One Relationship Doesn't Allow Inserting

I'm trying to setup a one-to-one mapping from my Users to the UserDetails table. Say I have the following tables in my database:
Users:
- UserID (PK, Identity)
- UserName
- Password
UsersDetails:
- UserID (PK, FK)
- FirstName
- LastName
I have created the following poco classes:
public class User {
public virtual int UserID { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual UserDetails Details { get; set; }
}
public class UserDetails {
public virtual int UserID { get; set; }
public virtual User User { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public UserDetails() {
}
public UserDetails(User user) {
User = user;
}
}
Which are fluently mapped (please note the xml mapping is very similar and if all you know is the xml mapping then I would still appreciate you guidance):
public class UserMap : ClassMap<User> {
public UserMap() {
Table("Users");
Id(x => x.UserID);
Map(x => x.UserName);
Map(x => x.Password);
HasOne(x => x.Details)
.Constrained()
.Cascade.All();
}
}
public class UserDetailsMap : ClassMap<UserDetails> {
public UserDetailsMap() {
Table("UsersDetails");
Id(x => x.UserID)
.GeneratedBy.Foreign("User");
HasOne(x => x.User)
.Constrained();
Map(x => x.FirstName);
Map(x => x.LastName);
}
}
Everything displays correctly but if I say:
var user = new User() { UserName = "Test", Password = "Test" };
user.Details = new UserDetails(user) { FirstName = "Test", LastName = "Test" };
session.Save(user);
I get the error:
"NHibernate.Id.IdentifierGenerationException: null id generated for: UserDetails."
I'd really appreciate it if someone could show me what I've done wrong. Thanks
Edit: Courtesy of Jamie Ide's suggestion. I have changed my User mapping to:
public class UserMap : ClassMap<User> {
public UserMap() {
Table("Users");
Id(x => x.UserID);
Map(x => x.UserName);
Map(x => x.Password);
References(x => x.Details, "UserID")
.Class<UserDetails>()
.Unique();
}
}
But now when i insert a user i get the error:
"System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection."
If i add Cascade.All() on to my Reference i receive the original error i was getting about the null id generated.
I think Constrained should only be specified in the UserDetailsMap, not in the UserMap. Try:
public class UserMap : ClassMap<User> {
public UserMap() {
Table("Users");
Id(x => x.UserID);
Map(x => x.UserName);
Map(x => x.Password);
HasOne(x => x.Details)
.Cascade.All();
}
}
EDIT:
See this and this. It appears that you have to map the relationship as many-to-one from the User side and one-to-one constrained from the UserDetails side to get lazy loading working with one-to-one. I don't know if this is different in NH3.
I am not sure the way you are mapping the ID property is correct. shouldnt it just be an autoincremented id and your mapping should be as follows:
Id(x=>x.UserId);
I dont know the idea behind using Foreign and how it fits into things here.. can you please illustrate the logic behind that?
I think you need to have the foreign key identity mapping in your User mapping instead of the UserDetails and the native one in the UserDetails. I have been unable to find a reference for it, though.
http://gorbach.wordpress.com/2010/09/24/fluent-onetoone/
HasOne(x => x.Details).Cascade.All().ForeignKey("UserDetails");
HasOne(x => x.User).Constrained();
var user = new User() { UserName = "Test", Password = "Test" };
user.Details = new UserDetails(user) { FirstName = "Test", LastName = "Test" };
user.Details.User = user;
session.Save(user);
After further research it appears that this won't work in version 2.0. I am now in a position to upgrade to version 3.0 where i believe this is now possible.