3
Exception:
System.Invalidcastexception: It is not possible to convert an object of type 'Nhibernate.Type.Manytoonetype' to type 'Nhibernate.Type.Componenttype''.
The classes involved are:
public class ClassePrincipal
{
public virtual long Codigo { get; set; }
public virtual string Atributo1 { get; set; }
public virtual EEnumeradorAbstrato EnumeradorAbstrato { get; set; }
public virtual SubClasse SubClasse { get; set; }
}
public class SubClasse
{
public virtual string Atributo1 { get; set; }
public virtual double Atributo2 { get; set; }
/// <summary>
/// Bi-direcionamento
/// </summary>
public virtual ClassePrincipal ClassePrincipal { get; set; }
}
The mappings:
public class ClassePrincipalMap : ClassMap<ClassePrincipal>
{
public ClassePrincipalMap()
{
Table("tb_classe_principal");
Id(ClassePrincipal => ClassePrincipal.Codigo)
.Not.Nullable()
.Column("pk_classe_principal")
.GeneratedBy.Sequence("tb_classe_principal_pk_classe_principal_seq");
Map(a => a.Atributo1).Column("atributo1");
Component(ClassePrincipal => ClassePrincipal.EnumeradorAbstrato,
componentPart =>
componentPart.Map(eEnumeradorAbstrato => eEnumeradorAbstrato.Identificador,
"enumerador_abstrato"));
HasOne(ClassePrincipal => ClassePrincipal.SubClasse)
.Cascade.All()
.Constrained()
.ForeignKey("fk_classe_principal");
}
}
public class SubClasseMap : ClassMap<SubClasse>
{
public SubClasseMap()
{
Table("tb_SubClasse");
Id(SubClasse => SubClasse.ClassePrincipal.Codigo)
.Column("fk_classe_principal")
.GeneratedBy.Foreign("ClassePrincipal.Codigo");
Map(SubClasse => SubClasse.Atributo1).Column("atributo1");
Map(SubClasse => SubClasse.Atributo2).Column("atributo2");
References(SubClasse => SubClasse.ClassePrincipal, "fk_classe_principal").Cascade.None();
}
}
Specifications:
In the database fk_classe_main in tb_SubClasse is primary_key;
The error appeared after I added the annotation ".GeneratedBy.Foreign("Classeprincipal.Codigo");".
The same occurs when I invoke the Session method. Save() right after the "select nextval('sequence');"
Thank you.
I’m not sure I understand, but your model says FK:
fk_classe_principal
, would also be the PK in the tabletb_SubClasse
, right? And you’d like to map that out to Nhibernate?– Fernando Leal
This, I realized that the error really happens due to annotation: ".GeneratedBy.Foreign("Classeprincipal.Codigo");". I’m trying to implement Generatedby.Hilo() to see the behavior. Do you know how it works? Because from this table that is "around" the main will be inserted first, and its id has to be the same as the main one.
– Pedro
I posted an answer, with the possible solution that I believe works for you, check if it is suitable to your problem and if it solves it?
– Fernando Leal