NHibernate: why doesn't my profiler query correspond to my fluent mapping? - nhibernate

I have this fluent mapping:
sealed class WorkPostClassMap : ClassMap<WorkPost>
{
public WorkPostClassMap()
{
Not.LazyLoad();
Id(post => post.Id).GeneratedBy.Identity().UnsavedValue(0);
Map(post => post.WorkDone);
References(post => post.Item).Column("workItemId").Not.Nullable();
References(Reveal.Property<WorkPost, WorkPostSheet>("Owner"), "sheetId").Not.Nullable();
}
parent class:
sealed class WorkPostSheetClassMap : ClassMap<WorkPostSheet>
{
public WorkPostSheetClassMap()
{
Id(sheet => sheet.Id).GeneratedBy.Identity().UnsavedValue(0);
Component(sheet => sheet.Period, period =>
{
period.Map(p => p.From, "PeriodFrom");
period.Map(p => p.To, "PeriodTo");
});
References(sheet => sheet.Owner, "userId").Not.Nullable();
HasMany(sheet => sheet.WorkPosts).KeyColumn("sheetId").AsList();
}
WorkItem class:
sealed class WorkItemClassMap : ClassMap<WorkItem>
{
public WorkItemClassMap()
{
Not.LazyLoad();
Id(wi => wi.Id).GeneratedBy.Assigned();
Map(wi => wi.Description).Length(500);
Version(wi => wi.LastChanged).UnsavedValue(new DateTime().ToString());
}
}
And when a collection of WorkPosts are lazy loaded from the owning work post sheet I get the following select statement:
SELECT workposts0_.sheetId as sheetId2_,
workposts0_.Id as Id2_,
workposts0_.idx as idx2_,
workposts0_.Id as Id2_1_,
workposts0_.WorkDone as WorkDone2_1_,
workposts0_.workItemId as workItemId2_1_,
workposts0_.sheetId as sheetId2_1_,
workitem1_.Id as Id1_0_,
workitem1_.LastChanged as LastChan2_1_0_,
workitem1_.Description as Descript3_1_0_
FROM "WorkPost" workposts0_
inner join "WorkItem" workitem1_ on workposts0_.workItemId=workitem1_.Id
WHERE workposts0_.sheetId=#p0;#p0 = 1
No, there are a couple of things here which doesn't make sence to me:
The workpost "Id" property occurs twice in the select statement
There is a select refering to a column named "idx" but that column is not a part of any fluent mapping.
Anyone who can help shed some light on this?

The idx column is in the select list because you have mapped Sheet.WorkPosts as an ordered list. The idx column is required to set the item order in the list. I'm not sure why the id property is in the select statement twice.
By the way, an unsaved value of 0 is the default for identity fields, so you can remove .UnsavedValue(0) if you want.

Related

For Fluent NHibernate experts: Join with where condition

SQL Server syntax is:
select tableAColumn1, tableAColumn2, tableBColumn1
from tableA, tableB
where ISNUMERIC(tableAColumn1) = 1
and CONVERT(INT, tableAColumn1) = tableBColumn1
and tableAColumn2 = 'something'
What would be the best way to achieve this in Fluent NHibernate? How many classes would I need to help get the resulting ClassMap and how would it look like?
Edit:
public class BarausInfoMap : ClassMap<BarausInfo>
{
public BarausInfoMap()
{
Table("BARAUS");
Id(x => x.nr);
Map(x => x.betrag);
Join("BARAUSLANG", m =>
{
m.Fetch.Join();
m.KeyColumn("Ula");
m.Map(x => x.bezeichnung);
m.Map(x => x.sprache);
m.Map(x => x.la);
this.Where("m.la = 'SPE'");
});
}
}
nr column is int and ula column is string, but I need to join those 2. also, the this.where refers to the outer table I guess, it should however refer to the inner table.
Maybe it's better to use separate entities and separate mapping, than you build query like
queryOver<BarausInfo>.JoinQueryOver(x => x.BarauslangObject, barauslangAlias, JoinType.InnerJoin, conjunction)
and the conjunction will contain the ISNUMERIC(tableAColumn1) = 1 and tableAColumn2 = 'something'. And n the BarausInfo Mapping you can spefify something like References(v => v.BarauslangObject).Formula("CONVERT(INT, tableAColumn1) = tableBColumn1"). Just find out how to specify columns in formula properly.

NHibernate 3.1 ignoring computed column formula

I have a class with two computed columns. The formulas are select statements that grab counts from other tables, like so:
private const string VOTES_FORMULA = "(select count(v.id) from Votes v where v.BusinessID = Id)";
private const string SURVEY_FORMULA = "(select cast((case when exists (select * from surveys s where s.businessid = Id) then 1 else 0 end) as bit))";
// in my bootstrap code...
mappings.Override<Business>(map =>
{
map.IgnoreProperty(x => x.IsNewRecord);
map.IgnoreProperty(x => x.IdString);
map.Map(x => x.UserPassword).CustomType<EncryptedStringType>();
map.Map(x => x.HasTakenSurvey).Formula(SURVEY_FORMULA).Not.Insert().Not.Update();
map.Map(x => x.Votes).Formula(VOTES_FORMULA).Not.Insert().Not.Update();
});
This was all working fine with Fluent NHibernate 1.1 (using NHibernate 2.1), but I just upgraded to 1.2 (using NH 3.1) and it appears that Fluent NHibernate is ignoring the formulas. I'm getting an "invalid column name" exception for the two fields HasTakenSurvey and Votes because its' trying to query the columns directly rather than executing the formulas as directed. An example query:
exec sp_executesql N'select TOP (#p0) business0_.Id as Id0_, business0_.UserPassword as UserPass2_0_, business0_.HasTakenSurvey as HasTaken3_0_, business0_.Votes as Votes0_, business0_.Origin as Origin0_, business0_.SecurityToken as Security6_0_, business0_.BusinessName as Business7_0_, business0_.BusinessType as Business8_0_, business0_.BusinessImageUrl as Business9_0_, business0_.BusinessDescription as Busines10_0_, business0_.EmployeeCount as Employe11_0_, business0_.OwnerFirstName as OwnerFi12_0_, business0_.OwnerLastName as OwnerLa13_0_, business0_.UserPosition as UserPos14_0_, business0_.BusinessAddress1 as Busines15_0_, business0_.BusinessAddress2 as Busines16_0_, business0_.BusinessCity as Busines17_0_, business0_.BusinessState as Busines18_0_, business0_.BusinessPostal as Busines19_0_, business0_.BusinessCountry as Busines20_0_, business0_.UserBusinessPhone as UserBus21_0_, business0_.UserMobilePhone as UserMob22_0_, business0_.UserEmailAddress as UserEma23_0_, business0_.UserIpAddress as UserIpA24_0_, business0_.OptInReminders as OptInRe25_0_, business0_.OptInOffers as OptInOf26_0_, business0_.OptInSms as OptInSms0_, business0_.Created as Created0_, business0_.Modified as Modified0_ from dbo.Businesses business0_ order by business0_.BusinessName asc',N'#p0 int',#p0=25
Did the implementation change? What am I doing wrong?
As noted in the comments ConventionBuilder.Property.Always(x => x.Column(x.Property.Name)) was adding the column to all properties (and overriding the formula).
Adding .Columns.Clear() to the mapping should remove the column, so:
mappings.Override<Business>(map =>
{
map.IgnoreProperty(x => x.IsNewRecord);
map.IgnoreProperty(x => x.IdString);
map.Map(x => x.UserPassword).CustomType<EncryptedStringType>();
map.Map(x => x.HasTakenSurvey).Formula(SURVEY_FORMULA).Not.Insert().Not.Update().Columns.Clear();
map.Map(x => x.Votes).Formula(VOTES_FORMULA).Not.Insert().Not.Update().Columns.Clear();
});
Columns.Clear() solution provided by #david duffet also didn't work for me. The getter of Formula is private and so you can't filter on the Formula property (you get method-group cannot be converted to value or something like that). NH3.3, FNH 1.3.
My solution - create a custom Attribute in my Model project - IsNHibernateFormulaPropertyAttribute, apply it to my formula properties, and then check for that attribute in my naming convention logic using reflection:
private bool IsFormula(IPropertyInstance instance)
{
var propInfo = instance.Property.DeclaringType.GetProperty(instance.Property.Name);
if (propInfo != null)
{
return Attribute.IsDefined(propInfo, typeof(IsNHibernateFormulaPropertyAttribute));
}
return false;
}
public void Apply(IPropertyInstance instance)
{
if (!IsFormula(instance))
{
instance.Column(Convert(instance.Property.Name));
}
}

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).

HasMany relation inside a Join Mapping

So, I'm having a problem mapping in fluent nhibernate. I want to use a join mapping to flatten an intermediate table: Here's my structure:
[Vehicle]
VehicleId
...
[DTVehicleValueRange]
VehicleId
DTVehicleValueRangeId
AverageValue
...
[DTValueRange]
DTVehicleValueRangeId
RangeMin
RangeMax
RangeValue
Note that DTValueRange does not have a VehicleID. I want to flatten DTVehicleValueRange into my Vehicle class. Tgis works fine for AverageValue, since it's just a plain value, but I can't seem to get a ValueRange collection to map correctly.
public VehicleMap()
{
Id(x => x.Id, "VehicleId");
Join("DTVehicleValueRange", x =>
{
x.Optional();
x.KeyColumn("VehicleId");
x.Map(y => y.AverageValue).ReadOnly();
x.HasMany(y => y.ValueRanges).KeyColumn("DTVehicleValueRangeId"); // This Guy
});
}
The HasMany mapping doesn't seem to do anything if it's inside the Join. If it's outside the Join and I specify the table, it maps, but nhibernate tries to use the VehicleID, not the DTVehicleValueRangeId.
What am I doing wrong?
Can you explain the average value column in the DTVehicleValueRange table? Isn't this a calculated value (i.e. no need to persist it)?
It looks like you have a many-to-many relationship between Vehicle and DTValueRange, which of course would not be mapped with a join, rather with a HasManyToMany call.
Ran into a similar issue today using a Map to create a view. The SQL generated showed it trying to do the HasMany<> inside the join based on the Id of the ParentThing and not WorkThing (same problem you were having)
After much mapping of head-to-desk it turns out adding the propertyref onto the hasmany solved it.
public class ThingMap : ClassMap<WorkThingView> {
public ThingMap() {
ReadOnly();
Table("ParentThing");
Id(x => x.ParentThingId);
Map(x => x.ParentName);
Join("WorkThing", join => {
join.KeyColumn("ParentThingId");
join.Map(m => m.FooCode);
join.Map(m => m.BarCode);
join.Map(x => x.WorkThingId);
join.HasMany(x => x.WorkThingCodes)
.Table("WorkThingCode").KeyColumn("WorkThingId").PropertyRef("WorkThingId")
.Element("WorkThingCode");
});
}
}

What's wrong with this Fluent NHibernate Configuration?

What's wrong with the following setup? The Where filter on the AutoPersistanceModel does not appear to be working and the table name convention does not appear to be working either. The error I'm evenually getting is "The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'property' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, jcs-cache, cache, id, composite-id' in namespace 'urn:nhibernate-mapping-2.2'." Here's my code:
public ISessionFactory BuildSessionFactory()
{
return Fluently.Configure()
.Database(
OracleConfiguration.Oracle9.ConnectionString(
c => c.FromConnectionStringWithKey("ConnectionString")))
.Mappings(m =>
{
m.AutoMappings.Add(GetAutoPersistanceModel);
m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
})
.BuildSessionFactory();
}
public AutoPersistenceModel GetAutoPersistanceModel()
{
return AutoPersistenceModel.MapEntitiesFromAssemblyOf<User>()
.Where(type => type.IsClass && !type.IsAbstract && type.Namespace == "Some.Namespace")
.ConventionDiscovery.Add<IConvention>(
Table.Is(x => "tbl" + x.EntityType.Name.Pluralize())
);
}
The exception is saying NHibernate has encountered a <property /> element first, which is invalid. The first element in an NHibernate hbm file should (nearly) always be an Id, so it seems the AutoPersistenceModel isn't finding your identifiers.
How are your Ids named in your entities? The AutoPersistenceModel expects them to be literally called Id, if they're anything different then it won't find them.
You can use the FindIdentity configuration option to override how the AutoPersistenceModel finds Ids, which can be useful if you're unable to modify your entities.
// if your Id is EntityId
.WithSetup(s =>
s.FindIdentity = property => property.DeclaredType.Name + "Id"
)
James is leading you correctly but his snippet is wrong.
.WithSetup(s=> s.FindIdentity = p => p.Name == "ID"));
Is what you're after! Replace "ID" with what ever your actual property is.