Hierarchical entity parent key in NHibernate ByCode - nhibernate

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"));

Related

NHibernate - Error dehydrating property value - updating entity

I'm having problem when saving an entity with association. Below is my code which gives the error
Fluent Class inherited from Fluent Migration
public override void Up() //Update your changes to the database
{
Create.Table("assinatura")
.WithColumn("id").AsInt32().Identity().PrimaryKey()
.WithColumn("usuario_id").AsInt32()
.WithColumn("isfreeplan").AsInt32() //1 sim 0 nao
.WithColumn("gratuito_datafinal").AsDateTime()
Create.Table("usuarios")
.WithColumn("id").AsInt32().Identity().PrimaryKey()
.WithColumn("nomecompleto").AsString(256) //Patricia dos Santos
.WithColumn("email").AsString(512) //patricia#gmail.com
.WithColumn("password").AsString(128) //123123123
Create.ForeignKey("IX_FK_AssinaturasUsuarios")
.FromTable("assinatura").ForeignColumn("usuario_id")
.ToTable("usuarios").PrimaryColumn("id");
}
Mapping of Table "Usuario"
public class UsuariosMap : ClassMapping<Usuario>
{
public enum Niveis { CADASTRADO = 0, REQUISITOU_PAGAMENTO = 1 }
public virtual int id { get; set; }
public virtual string nomecompleto { get; set; }
public virtual string email { get; set; }
public virtual string password { get; set; }
public UsuariosMap()
{
Table("usuarios");
Id(x => x.id, x => x.Generator(Generators.Identity));
Property(x => x.nomecompleto, x => x.NotNullable(true));
Property(x => x.email, x => x.NotNullable(true));
Property(x => x.password, x => x.NotNullable(true));
Bag(x => x.assinaturas, map => {
map.Table("assinatura");
map.Lazy(CollectionLazy.Lazy);
map.Inverse(true);
map.Key(k => k.Column(col => col.Name("usuario_id")));
map.Cascade(Cascade.All); //set cascade strategy
}, rel => rel.OneToMany());
}
Mapping of Table "Assinatura"
public class Assinatura
{
public virtual int Id { get; set; }
public virtual int usuario_id { get; set; }
public virtual int isfreeplan { get; set; }
public virtual DateTime gratuito_datafinal { get; set; }
public virtual Usuario usuario { get; set; }
}
public class AssinaturaMap : ClassMapping<Assinatura>
{
public AssinaturaMap()
{
Table("assinatura");
Id(x => x.Id, x => x.Generator(Generators.Identity));
Property(x => x.usuario_id, x => x.NotNullable(true));
Property(x => x.isfreeplan, x => x.NotNullable(true));
Property(x => x.gratuito_datafinal, x => x.NotNullable(true));
ManyToOne(x => x.usuario, x=>
{
x.Cascade(Cascade.DeleteOrphans);
x.Column("usuario_id");
x.ForeignKey("IX_FK_AssinaturasUsuarios");
});
}
}
When I try to update a User "Usuario" adding a new "Assinatura" I am getting an error
var user = Database.Session.Load<Usuario>(1);
var ass = new Assinatura
{
isfreeplan = 0,
gratuito_datafinal = DateTime.Now,
usuario = user
};
if (user != null)
{
user.assinaturas.Add(ass);
Database.Session.SaveOrUpdate(user);
}
An exception of type 'NHibernate.PropertyValueException' occurred in NHibernate.dll but was not handled in user code
{"Error dehydrating property value for Test.Models.Assinatura.usuario"}
Inner Exc: {"Parameter index is out of range."}
Property Name: usuario
I just want to do a basic one-to-many relationship between Usuario table and Assinature table (1 user has one or many assinaturas).
The exception:
Parameter index is out of range
is telling us, that we are working with one DB column twice. And that is because of this doubled mapping:
Property(x => x.usuario_id, x => x.NotNullable(true));
ManyToOne(x => x.usuario, x=>
{
x.Cascade(Cascade.DeleteOrphans);
x.Column("usuario_id");
...
It is ok to use one column for more properties (one value type, one reference).. but only for reading (loading values from DB)
For insert / update... we can use only one of these. And always is better to keep read/write reference, and property readonly
Property(x => x.usuario_id, x => {
x.NotNullable(true)
x.Insert(false)
x.Update(false)
})

NHibernate - Wrong Columns on Queries

I'm getting an intermittant problem with NHibernate where it generates a query for an entity, but replaces one of the columns with a column from completely different (and unrelated) entity.
It only ever replaces a single column, and is generally solved by restarting the application (though sometimes it takes a couple of attempts).
ASP.NET application (.NET 4.0)
SessionFactory created during Application_Start
NHibernate 3.3.1- All mappings/configuration done via Mapping By Code
Using Nhibernate Criteria
Any input on this would be much appreciated!
Entity
public class LiquiditySourceItem : RunDataEntity, IEntity<int>
{
public virtual int Id { get; protected internal set; }
public virtual int IdentID { get; protected internal set; }
public virtual string Portfolio { get; protected internal set; }
public virtual string ProfitCentre { get; protected internal set; }
public virtual DateTime? MaturityDate { get; protected internal set; }
public virtual string Curr1 { get; protected internal set; }
public virtual string Curr2 { get; protected internal set; }
public virtual decimal Reval { get; protected internal set; }
public virtual string ContractType { get; protected internal set; }
public virtual string ContractType2 { get; protected internal set; }
public virtual string ContractCode { get; protected internal set; }
public virtual decimal AmountSignedTradeUnit { get; protected internal set; }
public virtual decimal Amount2Signed { get; protected internal set; }
public virtual decimal SpotDelta { get; protected internal set; }
public virtual string TradeRevalCurr { get; protected internal set; }
}
Entity Mapping
public LiquiditySourceItemMap()
{
Id(x => x.Id, map => map.Column("RowId"));
Property(x => x.IdentID, map => map.Column("IdentID"));
Property(x => x.Portfolio, map => map.Column("Portfolio"));
Property(x => x.ProfitCentre, map => map.Column("ProfitCentre"));
Property(x => x.MaturityDate, map => map.Column("Con_Expiry"));
Property(x => x.BuySell, map => map.Column("BS"));
Property(x => x.Curr1, map => map.Column("Curr1"));
Property(x => x.Curr2, map => map.Column("Curr2"));
Property(x => x.Reval, map => map.Column("Reval"));
Property(x => x.ContractType, map => map.Column("ContractType"));
Property(x => x.ContractType2, map => map.Column("ContractType2"));
Property(x => x.ContractCode, map => map.Column("ContractCode"));
Property(x => x.AmountSignedTradeUnit, map => map.Column("AmountSignedTradeUnit"));
Property(x => x.Amount2Signed, map => map.Column("Amount2Signed"));
Property(x => x.ValSpot, map => map.Column("Val_Spot"));
Property(x => x.SpotDelta, map => map.Column("SpotDelta"));
Property(x => x.TradeRevalCurr, map => map.Column("Traderevalcurr"));
Property(x => x.SourceReport, map => map.Column("SourceReport"));
ManyToOne(x => x.RunContext, map => map.Column("RunContextID"));
Table("Staging.vw_Liquidity");
}
Report Entity
public class BusinessBreakdownStandardPosition : ReportRunDataEntity, IEntity<long>
{
public virtual long Id { get; set; }
public virtual decimal FinalNettingAmountUSD { get; set; }
public virtual decimal InitialChargeAmountUSD { get; set; }
public virtual BusinessBreakdownInitialPrr InitialPrr { get; set; }
public virtual IEnumerable<FinalInstrumentPosition> FinalInstrumentPositions { get; set; }
public virtual decimal CreditEventPaymentUSD { get; set; }
public virtual decimal ValuationChangeIncreaseUSD { get; set; }
public virtual decimal ValuationChangeDecreaseUSD { get; set; }
public virtual string ReportKey { get; set; }
public virtual decimal USDCharge { get; set; }
public virtual decimal USDChargeICG { get; set; }
public virtual string InstrumentType { get; set; }
}
Report Entity Mapping
public class BusinessBreakdownStandardPositionMap : ClassMapping<BusinessBreakdownStandardPosition>
{
public BusinessBreakdownStandardPositionMap()
{
Id(x => x.Id,
m =>
{
m.Column("BusinessBreakdownStandardPositionID");
m.Generator(Generators.HighLow,
g =>
g.Params(
new
{
table = "dbo.HiValue",
max_lo = 10000,
Where = string.Format("EntityName = 'BusinessBreakdownStandardPosition'")
}));
});
Property(x => x.FinalNettingAmountUSD, map => map.Column("FinalNettingAmountUSD"));
Property(x => x.InitialChargeAmountUSD, map => map.Column("InitialAmountUSD"));
Property(x => x.CreditEventPaymentUSD);
Property(x => x.ValuationChangeDecreaseUSD);
Property(x => x.ValuationChangeIncreaseUSD);
Property(x => x.USDCharge);
Property(x => x.USDChargeICG);
Property(x=>x.InstrumentType);
ManyToOne(p => p.RunContext, map => map.Column("ReportRunContextID"));
ManyToOne(p => p.InitialPrr, m =>
{
m.Column("InitialPrrID");
m.Cascade(Cascade.All);
});
Property(x => x.ReportKey);
Bag(x => x.FinalInstrumentPositions, collectionMapping =>
{
collectionMapping.Table("Reporting.BusinessBreakdownFinalInstrumentPositionStandardPositionMap");
collectionMapping.Cascade(Cascade.All);
collectionMapping.Key(k => k.Column("StandardPositionID"));
}, mapping => mapping.ManyToMany(y => y.Column("FinalInstrumentPositionID")));
Table("Reporting.BusinessBreakdownStandardPosition");
}
}
SQL Query, Generated By NHibernate
SELECT
this_.RowId AS RowId47_0_,
this_.IdentID AS IdentID47_0_,
this_.Portfolio AS Portfolio47_0_,
this_.ProfitCentre AS ProfitCe4_47_0_,
this_.Con_Expiry AS Con5_47_0_,
this_.BS AS BS47_0_,
this_.Curr1 AS Curr7_47_0_,
this_.Curr2 AS Curr8_47_0_,
this_.Reval AS Reval47_0_,
this_.ContractType AS Contrac10_47_0_,
this_.ContractType2 AS Contrac11_47_0_,
this_.ContractCode AS Contrac12_47_0_,
this_.AmountSignedTradeUnit AS AmountS13_47_0_,
this_.Amount2Signed AS Amount14_47_0_,
this_.Val_Spot AS Val15_47_0_,
this_.SpotDelta AS SpotDelta47_0_,
this_.InitialAmountUSD AS Initial17_47_0_,
this_.RunContextID AS RunCont18_47_0_,
this_.SourceReport AS Sou19_47_0_
FROM Staging.vw_Liquidity this_
Exception
System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'InitialAmountUSD'.
As you can see, nhibernate has replaced the LiquiditySourceItem column 'Traderevalcurr' with 'InitialAmountUSD', which belongs to the BusinessBreakdownStandardPosition entity. These entities have no relationship whatsoever. Otherwise, the SQL is exactly as you'd expect( including column order).
Observations
The wrong column is always a valid column in a different mapped entity
The wrong column will replace an existing one
The issue sometimes ocurrs between other entities. Again, there's no relationship between these
Any thoughts?
I asked the same question on the NHibernate Users Google Groups forum, and someone thinks they have worked out the root cause (and have also proposed a solution):
https://groups.google.com/forum/#!topic/nhusers/BZoBoyWQEvs
The problem code is in PropertyPath.Equals(PropertyPath) which attempts to determine equality by only using the hash code. This works fine for smaller code bases as the default Object.GetHashCode() returns a sequential object index. However, after garbage collection, these indices get reused as finalized objects are removed and new objects are created...which results in more than one object getting the same hashcode...Once garbage collection kicks in, property paths have a chance to share the same hashcode which means they will ultimately mix up their customizers for the colliding properties, thus the wrong column names...
If you want to fix this the bug, you can patch the NH source code:
If you have your own copy of the NH source, you can fix the bug by changing NHibernate/Mapping/ByCode/PropertyPath.cs line #66 from:
return hashCode == other.GetHashCode();
To:
return hashCode == other.GetHashCode() && ToString() == other.ToString();
Please check out the Google Group for full details of the issue.

NHibernate mapping by code: How to map IDictionary?

How can I map these Entities using mapping-by-code:
public class Foo
{
public virtual IDictionary<Bar, string> Bars { get; set; }
}
public class Bar
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
I found this thread, but it does not map an entity, only simple types. I tried many mappings, including automapping:
Map(x => x.Bars,
m =>
{
m.Key(k => k.NotNullable(true));
m.Cascade(Cascade.All);
},
But most of them throw these two errors:
Foreign key (Bars [idx])) must have same number of columns as the referenced primary key (Bars [FooId, idx]).
An association from the table FoosToStrings refers to an unmapped class: System.String.
Any help will be highly appreciated. Thanks. :)
i think this should work
Map(x => x.Bars,
entryMap => entryMap.Key(k => k.Column("foo_id")),
keymap => keymap.ManyToMany(m => m.Column("bar_Id")),
elementMap => elementMap.Element(m => m.Column("value")));

Nhibernate Conformist Mapping "Unable to determine type..."

The class:
public class SOPProcess : ISOPProcess
{
public virtual Guid Id { get; set; }
public virtual SOP SOP { get; set; }
public virtual ProcessType Type { get; set; }
public virtual SOPProcessInput Input { get; set; }
public virtual SOPProcessOutput Output { get; set; }
public virtual SOPProcessMeasures Measures { get; set; }
public virtual decimal YieldFactor { get; set; }
public virtual SOPProcess PreviousProcess { get; set; }
public virtual SOPProcess NextProcess { get; set; }
}
The Mapping:
public class SOPProcessMap : ClassMapping<SOPProcess>
{
public SOPProcessMap()
{
Id(s => s.Id, i => i.Generator(Generators.GuidComb));
Property(s => s.YieldFactor);
ManyToOne(s => s.SOP, m =>
{
m.Column("SopId");
m.Cascade(Cascade.All);
});
ManyToOne(s => s.Type, m =>
{
m.Column("ProcessTypeId");
m.Cascade(Cascade.All);
});
ManyToOne(s => s.NextProcess, m =>
{
m.Column("NextProcessId");
m.Cascade(Cascade.All);
});
ManyToOne(s => s.PreviousProcess, m =>
{
m.Column("PreviousProcessId");
m.Cascade(Cascade.All);
});
}
}
The Error:
NHibernate.MappingException: Could not determine type for: MES.ProcessManager.SOP.SOPProcess, MES.ProcessManager, for columns: NHibernate.Mapping.Column(id)
I hope it's something simple, this is my first project using the Conformist mapping, so maybe I'm just overlooking something.
From our discussion on the nhusers mailing list.
I ran across the same problems.
You haven't defined the type of relationship. See the line action => action.OneToMany()); in the mapping below.
public class SportMap : ClassMapping<Sport>
{
public SportMap()
{
Id(x => x.Id, map =>
{
map.Column("Id");
map.Generator(Generators.GuidComb);
});
Property(x => x.Name, map =>
{
map.NotNullable(true);
map.Length(50);
});
Bag(x => x.Positions, map =>
{
map.Key(k => k.Column(col => col.Name("SportId")));
map.Cascade(Cascade.All | Cascade.DeleteOrphans);
},
action => action.OneToMany());
Property(x => x.CreateDate);
Property(x => x.CreateUser);
Property(x => x.LastUpdateDate);
Property(x => x.LastUpdateUser);
}
}
It turned out that the problem was in my Set mappings in other classes. If you don't specify the action for the mapping, it throws this (misleading) error.

fluent nhibernate component one-to-many

I have couple of classes and want to map them correctly to database:
public class A
{
public virtual Guid Id { get; private set; }
public virtual ComponentClass Component { get; set; }
}
public class ComponentClass
{
public virtual IList<B> Elements { get;set; }
}
public class B
{
public virtual Guid Id { get; private set; }
public virtual DateTime Time { get; set; }
}
I map them using fluent mappings like that:
public class AMap : ClassMap<A>
{
public A() {
Id(x => x.Id);
Component(x => x.Component,
c => c.HasMany(x => x.Elements).Inverse().Cascade.All());
}
}
public class BMap : ClassMap<B>
{
public B() {
Id(x => x.Id);
Map(x => x.Time);
}
}
When I save my entity, I have class A mapped to one table and class B to another as expected.
But I have nulls in Component_id column.
Can you tell me what am I missing here?
I believe Components are supposed to be in the same table , as clearly stated in Ayende's blog post, as they serve only to make the data better represented as an object model. Be sure to read through his blog, it's probably one of the best nHibernate resources out there.
Ok, I've resolved my problem - I can use Id of my "parent" class. So the component mapping will become:
public class AMap : ClassMap<A>
{
public A() {
Id(x => x.Id);
Component(x => x.Component,
c => c.HasMany(x => x.Elements).Cascade.All().Column("Id"));
}
}
So obvious as I look at it now ... but It took me an hour.
If you have a one-to-many association direct to a collection of components (ie. without the ComponentClass wrapper as per the question) then you can map it directly:
HasMany(x => x.Elements)
.AsSet()
.Table("ElementTable")
.KeyColumn("KeyColumn")
.Cascade.All()
.Component(x =>
{
x.Map(c => c.Id);
x.Map(c => c.Time);
})
.LazyLoad();