Search code examples
c#nhibernatefluent-nhibernateautomapperhas-many

Error in mapping one-to-many with NHibernate


I am new to NHibernate and C#, so please be gentle!

I have the following two NHibernate entities:

public class Client : IEntity
{
    public virtual int Id { get; set; }

    public virtual IList<Residence> Residences { get; set; }
}

And

public class Residence : IEntity
{
     public virtual int Id { get; set; }

     public virtual int ClientId { get; set; }

     public virtual Client Client { get; set; }
}

and they have a one-to-many relationship from Client to Residence(each client can have multiple residence in their record).

Have this mappings with use automapping

public void Override(AutoMapping<Client> mapping)
{
     mapping.Id(c => c.Id).GeneratedBy.Native();
     mapping.HasMany(c => c.Residences).KeyColumn("Id").Inverse().Cascade.All();
     mapping.Table("Clients");
}

and

public void Override(AutoMapping<Residence> mapping)
{
     mapping.Id(p => p.Id);
     mapping.References(x => x.Client).Column("Id").Not.Nullable().Cascade.All();
     mapping.Table("Residences");
}

In my controller call IRepository of Client:

ClientModel newClient = ClientModel;

Client DomainModel = AutoMapper.Mapper.Map(newClient, new Client());

_clientService.Create(DomainModel);

Repository:

public class ClientService : IClientService
{
    private readonly IRepository<Client> _clientRepository;

    public void Create(Client client)
    {
        _clientRepository.Create(client);
    }
}

I have a problem with use Foreign key to Client.

This error: NHibernate.PropertyValueException: not-null property references a null or transient value ProjectBase.Domain.Entities.Residence.Client

I think this is because you try to use the ForeignKey Id Client that is not yet added to the table Client. But I do not know how to solve it. I need Help solved this error. Thank!


Solution

  • Solved it, changed mapping to:

    public void Override(AutoMapping<Client> mapping)
    {
         mapping.Id(c => c.Id).GeneratedBy.Native();
         mapping.HasMany(c => c.Residences).Inverse().Cascade.All();
         mapping.Table("Clients");
    }
    
    and
    
    public void Override(AutoMapping<Residence> mapping)
    {
         mapping.Id(p => p.Id);
         mapping.References(x => x.Client)
    }
    

    and add constructor in Clients

    public Client()
    {
        Residences = new List<Residence>();
    }
    

    Ty.