使用NHibernate映射一对多时出错

时间:2017-03-27 23:28:41

标签: c# nhibernate fluent-nhibernate automapper has-many

我是NHibernate和C#的新手,所以请保持温和!

我有以下两个NHibernate实体:

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

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

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

     public virtual int ClientId { get; set; }

     public virtual Client Client { get; set; }
}

他们与客户之间存在一对多的关系(每个客户可以在他们的记录中拥有多个住所)。

使用自动化

进行此映射
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");
}

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

在我的控制器中调用客户的IRepository:

ClientModel newClient = ClientModel;

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

_clientService.Create(DomainModel);

存储库:

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

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

使用外键到客户端时遇到问题。

此错误:NHibernate.PropertyValueException:not-null属性引用null或瞬态值ProjectBase.Domain.Entities.Residence.Client

我认为这是因为您尝试使用尚未添加到表Client的ForeignKey Id Client。但我不知道如何解决它。我需要帮助解决了这个错误。谢谢!

1 个答案:

答案 0 :(得分:0)

解决了它,将映射更改为:

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

并在客户端中添加构造函数

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