Many-to-one with formula - fluent-nhibernate

I have an NHibernate mapping file I want to convert to fluent. I'm stuck with this one particular case:
<many-to-one name="LastChildRevision" update="false" not-found="ignore" access="readonly" fetch="join">
<formula>(SELECT TOP(1) CHILD_REVISION.CHILD_REVISION_ID FROM CHILD_REVISION WHERE CHILD_REVISION.PARENT_ID = PARENT_ID ORDER BY CHILD_REVISION.REVISION_NUMBER DESC)</formula>
</many-to-one>
My class has:
public virtual IList<ChildRevision> ChildRevisions { get; set; }
public virtual ChildRevision LastChildRevision
{
get
{
return this.ChildRevisions.OrderBy(o => o.RevisionNumber).LastOrDefault();
}
}
How can I translate this to Fluent NHibernate? When I try this:
References(x => x.LastChildRevision)
.Formula("(SELECT TOP(1) CHILD_REVISION.CHILD_REVISION_ID FROM CHILD_REVISION WHERE CHILD_REVISION.PARENT_ID = PARENT_ID ORDER BY CHILD_REVISION.REVISION_NUMBER DESC)")
.Access
.ReadOnly()
.Fetch
.Join();
I get this:
Invalid column name 'LastChildRevision_id'.
Thanks!

I know I asked this question a long time ago, but I decided to revisit Fluent NHibernate, and here's what I came up with:
References(x => x.LastChildRevision)
.Column("PARENT_ID")
.Not.Insert()
.Not.Update()
.Access.ReadOnly()
.NotFound.Ignore()
.Cascade.None()
.Formula("(SELECT TOP(1) CHILD_REVISION.CHILD_REVISION_ID FROM CHILD_REVISION WHERE CHILD_REVISION.PARENT_ID = PARENT_ID ORDER BY CHILD_REVISION.REVISION_NUMBER DESC)");

there was a bug you might hit. Try clearing the columns first
References(x => x.LastChildRevision)
.Columns.Clear()
.Formula("(SELEC ...

Related

Fluent NHibernate Child collection persistence issues

I have the following mapping classes (only the relevant part copied):
public class CardTemplateMapping : ClassMap<CardTemplate>
{
public CardTemplateMapping()
{
Table("cardtemplate");
Id(x => x.Id)
.Column("id")
.GeneratedBy.Native();
HasMany(x => x.CostStructures)
.KeyColumn("cardtemplate_id")
.Cascade.All();
}
}
public class CostStructureMapping : ClassMap<CostStructure>
{
public CostStructureMapping()
{
Table("coststructure");
Id(x => x.Id)
.Column("id")
.GeneratedBy.Native();
References(x => x.CardTemplate)
.Column("cardtemplate_id");
HasMany(x => x.CostComponents)
.KeyColumn("coststructure_id")
.Cascade.AllDeleteOrphan();
}
}
public class CostStructureComponentMapping : ClassMap<CostStructureComponent>
{
public CostStructureComponentMapping()
{
Table("CostStructureComponent");
Id(x => x.Id)
.Column("id")
.GeneratedBy.Native();
References(x => x.CostStructure)
.Column("coststructure_id");
References(x => x.ResourceType)
.Column("resourcetype_id");
}
}
Nhibernate loads the relations as I intended. But two parts of the Mapping seem a bit weird (either that or my expectations are weird).
First:
CostStructure structure = new CostStructure() { CardTemplate = template };
template.CostStructures.Add(structure);
Session.Save(template);
Session.Flush();
This does not save the new CostStructure instance. Why?
Second one: Assuming I have loaded a CardTemplate having a CostStructure containing three CostStructureComponent entities. Now I want to remove one of those CostStructureComponents from the CostStructure.
I tried the following :
costStructure.CostComponents.Remove(component);
component.CostStructure = null;
session.Save(template)
Now, I know that explicitly deleting explicitly works, but shouldn't the DeleteOrphan part also assert that the component, now without CostStructure to reference, is deleted? Instead, NHibernate tries to perform the following update:
UPDATE CostStructureComponent
SET amount = #p0,
coststructure_id = #p1,
resourcetype_id = #p2
WHERE id = #p3;
#p0 = 1 [Type: Int32 (0)],
#p1 = NULL [Type: Int64 (0)],
#p2 = 5 [Type: Int64 (0)],
#p3 = 13 [Type: Int64 (0)]
Could it be Equals / GetHashCode have been implemented the wrong way?
Sorry, it's late, been a long day and so forth...If I'm talking gibberish, please let me know...
All the answers are hidden in one setting .Inverse()
public CardTemplateMapping()
{
HasMany(x => x.CostStructures)
.KeyColumn("cardtemplate_id")
.Cascade.All()
.Inverse(); // HERE this setting
And here:
public CostStructureMapping()
{
..
HasMany(x => x.CostComponents)
.KeyColumn("coststructure_id")
.Cascade.AllDeleteOrphan()
.Inverse(); // and HERE and everywhere on HasMany()
Try to find some articles about this setting, but in general: If mapped as inverse, NHibernate is ready to do much better SQL Statements, because it is working with other end of relation...
Some sources:
19.5.2. Lists, maps, idbags and sets are the most efficient collections to update cite:
However, in well-designed NHibernate domain models, we usually see that most collections are in fact one-to-many (comment: HasMany in Fluent) associations with inverse="true". For these associations, the update is handled by the many-to-one (comment: References in Fluent) end of the association, and so considerations of collection update performance simply do not apply.
6.2. Mapping a Collection
inverse (optional - defaults to false) mark this collection as the "inverse" end of a bidirectional association

NHibernate still issues update after insert

I have a very simple unidirectional mappings. see below:
public ContactMap()
{
Id(x => x.Id).GeneratedBy.Assigned();
Map(x => x.Name);
References(x => x.Device);
HasMany(x => x.Numbers)
.Not.Inverse()
.Not.KeyNullable()
.Cascade.AllDeleteOrphan()
.Not.LazyLoad()
.Fetch.Subselect();
Table("Contacts");
}
public PhoneNumberMap()
{
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Number);
Table("ContactNumbers");
}
According to this post after nhibernate 3 and above, setting key as non-nullable should fix the insert-update issue (The issue when NHibernate issues an insert with foreign key set to null and then an update to update the foreign key to correct value), but this is not the case for me. When I set the key as not nullable, NHibernate issues a correct insert statement
INSERT INTO ContactNumbers
(Number,
ContactId)
VALUES ('(212) 121-212' /* #p0 */,
10 /* #p1 */);
As you can see, it inserts ContactId field, but after that, it still issues update statement
UPDATE ContactNumbers
SET ContactId = 10 /* #p0 */
WHERE Id = 34 /* #p1 */
So to clarify the problem. NHibernate inserts Contact row with foreign key assigned correctly and after that, it issues an update statement to update the foreign key (ContactId) which is redundant.
How can I get rid of this redundant update statement?
Thanks.
BTW, I'm using latest version of NHibernate and Fluent NHibernate. The database is SQLite
You have to set "updatable"=false to your key to prevent update.
public ContactMap()
{
Id(x => x.Id).GeneratedBy.Assigned();
Map(x => x.Name);
References(x => x.Device);
HasMany(x => x.Numbers)
.Not.Inverse()
.Not.KeyNullable()
.Not.KeyUpdate() // HERE IT IS
.Cascade.AllDeleteOrphan()
.Not.LazyLoad()
.Fetch.Subselect();
Table("Contacts");
}
You can't as of 3.2.0 BETA.
In v3.2.0 BETA an improvment to one-to-many introduced this anomaly to uni-directional one-to-many relationships (actually I am not sure if anormaly is what you would call this).
Before 3.2 you would need to set the foreign key to allow nulls for this type of relationship to work. So I would ignore the fact that this happens and just go with it. Otherwise you will need to change it to a fully bi-directional relationship.
[NH-941] - One-Many Requiring Nullable Foreign Keys
Release notes or JIRA issue
edit Also the answer to the post you point to is to fix save null-save-update rather than fixing the addtional update
Try setting inverse to true on the mapping and assigning the relationship in code.
Inverse means that the child is responsible for holding the ID of the parent.
e.g.
var contact = new Contact();
var phoneNumber = new PhoneNumber();
phoneNumber.Contact = contact;
That way, when you do the insert for the PhoneNumber record, NH can insert the ContactId without having to do a separate update.
That's what I used to do in NH 2, I would assume the behaviour still works the same in 3.
I don't know if you really can get rid of it.
Try using another id generator as native. It forces NH to insert the record only to get the id. The id is used for every entity in the session, so it can't do the insert later. It may case subsequent updates. Use hi-lo or something similar.
Edit
Why aren't you using a component in this case? You don't need to map the phone number separately, if they consist only of a number. Something like this (I'm not a FNH user, so it may be wrong):
public ContactMap()
{
Id(x => x.Id).GeneratedBy.Assigned();
Map(x => x.Name);
References(x => x.Device);
HasMany(x => x.Numbers)
.Not.Inverse()
.Not.KeyNullable()
.Cascade.AllDeleteOrphan()
.Not.LazyLoad()
.Fetch.Subselect()
.Component(c =>
{
Map(x => x.Number);
})
.Table("ContactNumbers");
Table("Contacts");
}
It is what Trevor Pilley said. Use inverse="true". If you choose not to have inverse="true", this is the consequence of that choice. You can't have it both ways.

Optional many-to-one/References results in foreign key violations on insert

I currently have the following relationship: ProductUom -> ProductImage
They both have the same primary keys: PROD_ID and UOM_TYPE
I have them mapped like this:
public ProductUomMap()
{
Table("PROD_UOM");
CompositeId()
.KeyReference(x => x.Product, "PROD_ID")
.KeyProperty(x => x.UomType, "UOM_TYPE");
References(x => x.Image)
.Columns(new string[] { "PROD_ID", "UOM_TYPE" })
.Not.Update()
.Not.Insert()
.NotFound.Ignore()
.Cascade.All();
}
public ProductImageMap()
{
Table("PROD_UOM_IMAGE");
CompositeId()
.KeyReference(x => x.ProductUom, new string[] {"PROD_ID", "UOM_TYPE"});
Map(x => x.Image, "PROD_IMAGE").Length(2147483647);
}
Whenever I create a ProductUom object that has a ProductImage it tries to insert the ProductImage first which results in a foreign key violation. I swear this was working at one time with the mapping that I have but it doesn't now.
I need the ProductImage to be a Reference (many-to-one) because the relationship here is optional and I want to be able to lazy load product images. The inserts do work correctly if I use a HasOne (one-to-one) mapping but the I cannot lazy load when I do this and querying a ProductUom seems to cause issues.
Is there something that I'm missing here? How can this mapping be modified to get what I want?
can you use LazyLoaded Properties? Then you could use something like this
Join("PROD_UOM_IMAGE", join =>
{
join.KeyColumn("PROD_ID", "UOM_TYPE");
join.Optional();
join.Map(x => x.Image, "PROD_IMAGE").Length(2147483647).LazyLoad();
}
another option is:
Id().GeneratedBy.Foreign(x => x.ProductUom);
can't test it here though, i'm writing on Mobile

NHibernate using wrong table alias

I am trying to filter a collection based on a foreign key. I have two classes which are mapped with
public class GroupPriceOverrideMap:ClassMap<GroupPriceOverride>
{
public GroupPriceOverrideMap()
{
CompositeId()
.KeyReference(x => x.Service,"ServiceCode")
.KeyReference(x => x.CustomerAssetGroup, "GroupID");
Map(x => x.Price);
Table("accGroupPriceOverride");
}
}
public class CustomerAssetGroupMap:ClassMap<CustomerAssetGroup>
{
public CustomerAssetGroupMap()
{
Id(x => x.GroupID).Unique();
Map(x => x.Description);
References(x => x.Customer).Column("CustomerID");
HasMany<GroupPriceOverride>(x => x.PriceOverrides).KeyColumn("GroupID");
Table("accCustAssetGroup");
}
}
I query it using
_session.Linq<GroupPriceOverride>.Where(x => x.CustomerAssetGroup.GroupID == groupID)
However this is generating
SELECT this_.ServiceCode as ServiceC1_9_0_, this_.GroupID as GroupID9_0_, this_.Price as Price9_0_ FROM accGroupPriceOverride this_ WHERE customeras1_.GroupID = #p0
there where clause is referencing a table alias which doesn't exist(customeras1). This is probably an alias for crossing with customerassetgroup but there is no need to perform that cross. I'm sure that it is just something in my mapping with is wrong but I can't find it. I've tried various column renaming in case the presence of GroupID in both tables was causing problems but that didn't fix it. Any ideas?
Edit
I found that if I queried doing
_session.Linq<CustomerAssetGroup>().Where(x => x.GroupID == groupID).FirstOrDefault().PriceOverrides;
then I got the correct result. I also found that if I saved a GroupPriceOverride and then queried for it using HQL then it wouldn't be found but I could still find the entity by loading the parent and looking at its collection of overrides.
_session.CreateQuery("FROM GroupPriceOverride i").List().Count;//returns 0
_session.CreateQuery("FROM CustomerAssetGroupi").List().FirstOrDefault().PriceOverrides.Count;//returns 1
Looks like a bug in the old LINQ provider. Could you file a bug here:
https://nhibernate.jira.com/secure/Dashboard.jspa
You might be able to get around it via:
_session.Linq<GroupPriceOverride>.Where(x => x.CustomerAssetGroup == group)
and let NHibernate figure out the ID. If you don't have the group already, you could do this:
var group = _session.Load<CustomerAssetGroup>(groupID);
_session.Linq<GroupPriceOverride>.Where(x => x.CustomerAssetGroup == group)
The ISession.Load(id) will only generate a proxy, but won't actually hit the database until you access a property (which you wouldn't be since you're just using it to specify the ID).

nhibernate generate left outer join on many-to-one entity

i'm using nHibernate 2.1.2 and relized that nhibernate will generate left outer join on nested many-to-one entities. it seems start generate left-outer-join on 3rd nested note onwards which start from entity Organization. i have set following in the mapping file to force use inner-join, has anything i missed out in the mapping file? really hope somebody could give me a hint on this. appreciate any helps!
lazy="false" fetch="join"
Example Entites and Relationships:
Sales Record - Employee - Organization
nhibernate generate:
select...
from sales
inner join employee
left outer join organization
Sales.hbm.xml
<many-to-one name="Employee" insert="true" update="true" access="field.pascalcase-underscore" not-null="true" lazy="false" fetch="join"/>
<column name="EmployeeId" not-null="true"/>
</many-to-one>
Employee.hbm.xml
<many-to-one name="Organization" insert="true" update="true" access="field.pascalcase-underscore" not-null="true" lazy="false" fetch="join"/>
<column name="OrgId" not-null="true"/>
</many-to-one>
If NHibernate does an inner join you don't ID from a child and ID from a parent table (but they're the same).
Example:
TableParent (ID, Name)
TableChild (ID, ID_TableParent, ....)
If nHibernate does an inner join, you get:
select c.ID, c.ID_TableParent, p.Name
from TableChild c
inner join TableParent p on p.ID = c.ID_TableParent
If nHibernate does an left outer join, you get:
select c.ID, c.ID_TableParent, p.ID, p.Name
from TableChild c
left outer join TableParent p on p.ID = c.ID_TableParent
And because of the inner workings of NHibernate it can then create 2 entities from the second query. One entity for TableChild and one for TableParent.
In the first query you'd only get TableChild entity and in some cases the p.Name would be ignored (probalby on the second level) and it would requery the database on checking the property that references TableParent.
I found out this when I wanted to load a tree structure with only one hit to the database:
public class SysPermissionTree
{
public virtual int ID { get; set; }
public virtual SysPermissionTree Parent { get; set; }
public virtual string Name_L1 { get; set; }
public virtual string Name_L2 { get; set; }
public virtual Iesi.Collections.Generic.ISet<SysPermissionTree> Children { get; private set; }
public virtual Iesi.Collections.Generic.ISet<SysPermission> Permissions { get; private set; }
public class SysPermissionTree_Map : ClassMap<SysPermissionTree>
{
public SysPermissionTree_Map()
{
Id(x => x.ID).GeneratedBy.Identity();
References(x => x.Parent, "id_SysPermissionTree_Parent");
Map(x => x.Name_L1);
Map(x => x.Name_L2);
HasMany(x => x.Children).KeyColumn("id_SysPermissionTree_Parent").AsSet();
HasMany(x => x.Permissions).KeyColumn("id_SysPermissionTree").AsSet();
}
}
}
And the query I used was this:
SysPermissionTree t = null;
SysPermission p = null;
return db.QueryOver<SysPermissionTree>()
.JoinAlias(x => x.Children, () => t, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.JoinAlias(() => t.Permissions, () => p, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.Where(x => x.Parent == null)
.TransformUsing(Transformers.DistinctRootEntity)
.List();
With NHibernate.SqlCommand.JoinType.LeftOuterJoin. Because if I used InnerJoin the structure didn't load with only one query. I had to use LeftOuterJoin, so that NHibernate recognized the entities.
SQL Queries that executed were:
SELECT this_.ID as ID28_2_, this_.Name_L1 as Name2_28_2_, this_.Name_L2 as Name3_28_2_, this_.id_SysPermissionTree_Parent as id4_28_2_, t1_.id_SysPermissionTree_Parent as id4_4_, t1_.ID as ID4_, t1_.ID as ID28_0_, t1_.Name_L1 as Name2_28_0_, t1_.Name_L2 as Name3_28_0_, t1_.id_SysPermissionTree_Parent as id4_28_0_, p2_.id_SysPermissionTree as id4_5_, p2_.ID as ID5_, p2_.ID as ID27_1_, p2_.Name_L1 as Name2_27_1_, p2_.Name_L2 as Name3_27_1_, p2_.id_SysPermissionTree as id4_27_1_ FROM [SysPermissionTree] this_ left outer join [SysPermissionTree] t1_ on this_.ID=t1_.id_SysPermissionTree_Parent left outer join [SysPermission] p2_ on t1_.ID=p2_.id_SysPermissionTree WHERE this_.id_SysPermissionTree_Parent is null
SELECT this_.ID as ID28_2_, this_.Name_L1 as Name2_28_2_, this_.Name_L2 as Name3_28_2_, this_.id_SysPermissionTree_Parent as id4_28_2_, t1_.ID as ID28_0_, t1_.Name_L1 as Name2_28_0_, t1_.Name_L2 as Name3_28_0_, t1_.id_SysPermissionTree_Parent as id4_28_0_, p2_.ID as ID27_1_, p2_.Name_L1 as Name2_27_1_, p2_.Name_L2 as Name3_27_1_, p2_.id_SysPermissionTree as id4_27_1_ FROM [SysPermissionTree] this_ inner join [SysPermissionTree] t1_ on this_.ID=t1_.id_SysPermissionTree_Parent inner join [SysPermission] p2_ on t1_.ID=p2_.id_SysPermissionTree WHERE this_.id_SysPermissionTree_Parent is null
where the first query is left outer join and we get 2 extra fields: t1_.id_SysPermissionTree_Parent as id4_4_, t1_.ID as ID4_
So what I'm trying to tell you is that if you use NHibernate then left outer join is sometimes a must to comply with inner workings of NHibernate.