Consider following class structure.
public abstract class Animal
{
public string SomeData { get; set; }
public IList<AnimalProperty> AnimalProperties { get; set; }
public IList<OtherAnimalProperty> OtherAnimalProperties { get; set; }
}
public class Dog: Animal
{
public DogProperty DogProperties { get; set; }
}
With following mapping for the Dog class
HasOne(x => x.DogProperties).ForeignKey("Id");
I now have following query to retrieve a list of objects of type Animal.
list = session.QueryOver<Animal>()
.WhereRestrictionOn(e => e.SomeData).IsIn(someList.ToArray())
.Fetch(e => e.AnimalProperties).Default
.Fetch(e => e.OtherAnimalProperties).Default
.List();
My list now contains an object of type Dog (as expected), but the DogProperties property is null. Meaning, the one-to-one class defined in the mapping is not initialized.
However, NHibernate generated a nice joined query that retrieves also the DogProperty data from the database. It just does not create the class through this query.
SELECT this_.Id as Id0_1_, this_.Name as Name0_1_, this_.DogName as DogName0_1_,
this_.AnimalType as AnimalType0_1_, dogpropert2_.Id as Id1_0_,
dogpropert2_.MyProperty as MyProperty1_0_
FROM [Animal] this_ left outer join [DogProperties] dogpropert2_
on this_.Id=dogpropert2_.Id
Can anyone elaborate what I'm missing here? Or is this a bug/default behavior of NHibernate QueryOver?
Related
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)
I have a problem with mapping in NHibernate.
The Order table has the Invoice_Id column which is the nullable FK to the Invoice table.
The problem is, when I load an Invoice which Id exists in the Order table, I see that ConnectedOrder property is null, why?
public class Invoice
{
public virtual Order ConnectedOrder { get; set; }
}
public class Order
{
public virtual Invoice ConnectedInvoice { get; set; }
}
public class InvoiceMap : ClassMap<Invoice>
{
public InvoiceMap()
{
this.References(x => x.ConnectedOrder).Nullable();
}
}
public class OrderMap : ClassMap<Order>
{
public OrderMap()
{
this.References(x => x.ConnectedInvoice).Nullable();
}
}
edit
I've changed my classes and mappings like Radim Köhler said, then I found that topic
Fluent NHibernate One-To-Many Mapping
and there was the need to also add:
this.HasMany(x => x.Orders)
.KeyColumn("Invoice_id")
.Inverse()
.Cascade
.AllDeleteOrphan();
and now it works
You may not like it, but the table structure described above, is not representing Entity relations you've created (so called one-to-one).
In case, that one table contains column referencing the another table (FK), we have scenario:
Each Order has exactly one (or null) Invoice. (many-to-one)
Invoice can be referenced by none or one or many Orders. (one-to-many)
That means, that we should express Entities like this:
public class Invoice
{ // many orders could reference us
public virtual IList<Order> Orders { get; set; }
...
public class Order
{ // unchanged
public virtual Invoice ConnectedInvoice { get; set; }
...
And the mapping should be:
public InvoiceMap()
{ // HasMany is one-to-many
this.HasMany(x => x.Orders)
...
}
public OrderMap()
{ // References is many-to-one
this.References(x => x.ConnectedInvoice).Nullable();
...
I want to combine table-per-class and table-per-hierarchy strategies using fluent nhibernate or nhibernate itself(I mean hbm files), but I don't know how. I prefer fluent over hbm but if it's impossible, then hbm is also fine. I tested this by introducing Entity as ClassMap and all other as SubClassMap in fluent but then in hbm files generated by fluent, Entity was a class and all other were joined-classes which is not what I want. I will describe the problem in more detail below.
Class hierarchy:
public class Entity
{
public int ID { get; set; }
public string Name { get; set; }
}
public abstract class Person : Entity
{
public string Phone { get; set; }
}
public class SystemUser : Person
{
public string Password { get; set; }
}
I want to have one table for entity and one for person and all kinds of it(all its subclasses).I mean I want to use table-per-class strategy for Entity and table-per-hierarchy strategy for Person and SystemUser classes. Database structure is something like this:
EntityTable(ID(PK),Name)
PersonTable(EntityID(PK,FK),Phone,Password)
any help appreciated.
if EntityTable Id is not database generated (which is discouraged by NH anyways) you can use the trick
public PersonMap : ClassMap<Person>
{
public PersonMap()
{
Table("PersonTable");
Id(p => p.Id, "EntityID").GeneratedBy.HiLo("100");
DiscriminateSubClassesOnColumn("PersonType");
Map(x => x.Phone);
Join("EntityTable", join =>
{
join.KeyColumn("ID");
join.Map(p => p.Name);
});
}
}
public SystemUserMap : SubclassMap<SystemUser>
{
public SystemUserMap()
{
Map(x => x.Password);
}
}
I'm using Nhibernate with Fluent and I encounter an issue with inheritance.
Here my DB schema
TABLE Base
IDBASE (PK)
Field1
TYPE
TABLE T1
IDBASE (PK and FK)
Field2
Field3 ...
My mapping files are :
public class BaseMap: ClassMap<BASE>
{
public BaseMap()
{
Id(x => x.Id, "IDBASE").GeneratedBy.Identity();
Map(x => x.Field1);
DiscriminateSubClassesOnColumn("TYPE");
}
}
public class T1Map: SubclassMap<T1>
{
public T1Map()
{
Table("T1");
KeyColumn("IDBASE");
DiscriminatorValue("T1");
Map(x => x.Field2).Not.Nullable();
Map(x => x.Field3).Not.Nullable();
}
}
I use FluentMappings instead of AutoMapping.
Here my entities :
public abstract class BASE
{
public virtual long IdBase{ get; set; }
public virtual string Field1 { get; set; }
}
public class T1: BASE
{
public virtual string Field2 { get; set; }
public virtual string Field3 { get; set; }
}
T1 entity inherits from BASE entity, the issue is when I try to get a row NHibernate try to select Field2 and Field3 on the Base Table whereas they should be selected on T1 Table.
I've tried dozens of hacks but it still doesn't work, if anyone as an idea it would be very helpful.
Thanks a lot.
You're specifying a discriminator, that implies that the inheritance structure should be a table-per-class-hierarchy; you won't have two tables with this setup, you'll have a single table with everything in (hence why the select is hitting the same table for all the columns).
If you remove the DiscriminateSubclassesOnColumn call, that'll put your mappings into a table-per-class, so you'll have your desired structure.
Actually I really need the DiscriminateSubclassesOnColumn so I found an other solution, in my inherited entity I do the mapping with the join like this :
public class T1Map: SubclassMap<T1>
{
public T1Map()
{
Join("T1", y =>
{
y.KeyColumn("IDBASE");
y.Map(x => x.Field2).Not.Nullable();
y.Map(x => x.Field3).Not.Nullable();
});
}
}
And it works fine, I can keep the Discriminator column on my base class.
Thanks
I'm trying to use the table-per-subclass (which fluent-nhibernate automaps by default) with a class structure like the following:
public class Product
{
public virtual int Id{ get; set; }
public virtual string Title{ get; set; }
}
public class ProductPackage : Product
{
public ProductPackage(){ Includes = new List<Product>(); }
public virtual IList<Prodcut> Includes{ get; private set; }
[EditorBrowsable( EditorBrowsableState.Never )]
public class ProductPackageAutoOverride : IAutoMappingOverride<ProductPackage>
{
public void Override( AutoMap<ProductPackage> mapping )
{
mapping.HasManyToMany( x => x.Includes )
.WithTableName( "IncludesXProduct" )
.WithParentKeyColumn( "ProductId" )
.WithChildKeyColumn( "IncludesProductId" )
.Cascade.SaveUpdate();
}
}
}
Instead of adding a new table "IncludesXProduct" to represent the many-to-many mapping, it adds a property "ProductPackageId" to the Product table. Of course persisting to this schema doesn't work.
Have I missed something simple or is this type of thing not really supported by NHibernate?
It is possible to do this with NHibernate. Unfortunately my fluent syntax isn't very good, but it looks like FNH is somehow regarding the relationship as a many-to-one rather than a many-to-many.
If you tag your question with "fluent-nhibernate" then you may get more knowledgeable people answering.