Fluent Nhibernate - Composite key mapping one to many

Asked

Viewed 786 times

7

I’m having a problem mapping an entity through Fluent Nhibernate.

I have a 1-N relation to the two tables in the bank having composite keys.

When I try to list my entity User an error comes back, but this only happens when I create the relationship with the entity Accessodepartamento

User

public class UsuarioMap : ClassMap<Usuario>
{
    public UsuarioMap()
    {
        CompositeId()
            .KeyProperty(x => x.Email, "Usuario")
            .KeyReference(x => x.Empresa, "CodEmp")
            .KeyProperty(x => x.CodigoFilial, "Filial");

        Map(x => x.Nome, "Nome");
        Map(x => x.AcessoTodosDepartamentos, "AllDeptos");
        Map(x => x.AcessoTodosPedidos, "allPed");
        Map(x => x.Email, "email");
        Map(x => x.NivelUsuario, "UsrTipo")
            .CustomType<NivelUser>();
        Table("Usuario");

        References<Empresa>(x => x.Empresa, "CodEmp");
        References<CentroCusto>(x => x.CentroCusto, "CCusto");
        References<Departamento>(x => x.Departamento)
            .Column("CodDep");

        HasMany<AcessoDepartamento>(x => x.AcessoDepartamentos)
            .KeyColumn("AcessoDep");
    }
}

Accessodepartamentomap

public class AcessoDepartamentoMap : ClassMap<AcessoDepartamento>
{
    public AcessoDepartamentoMap()
    {
        CompositeId()
            .KeyProperty(x => x.AcessoDep, "AcessoDep")
            .KeyReference(x => x.Departamento, "CodDep");

        Map(x => x.CodigoFilial, "Filial");
        Table("AcessoDep");

        References<Departamento>(x => x.Departamento)
            .Column("CodDep");
        References<Empresa>(x => x.Empresa)
            .Column("CodEmp");
    }
}

I’ve tried everything I’ve seen through the research I’ve done and nothing so far:

Foreign key (FK44A92FD8F30CB372:Acessodep [Acessodep])) must have same number of Columns as the referenced Primary key (Usuario [Usuario, Codemp, Branch Office])

How can I solve?

  • Your AcessoDepartamento also has a column called Filial? The detail is that Nhibernate is trying to add a FOREIGN KEY to Usuario, but you need to reference the three columns that make up the user.

  • I tried to reference the three columns as the error said, in which case the error stopped appearing, but did not pull the reference from the AcessoDepartamento. Of these three columns the AcessoDepartamento just doesn’t have the Usuario, the other two (Filial and CodEmp) he has.

1 answer

3


I found that answer in Stack Overflow in English, but in my experience something like this helps and even solves:

HasMany<AcessoDepartamento>(x => x.AcessoDepartamentos)
  .KeyColumns.Add("AcessoDep", "CodDep").Cascade.All(); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.