我的NHibernate映射有什么问题?

时间:2013-09-25 14:39:50

标签: c# nhibernate nhibernate-mapping

我有一个表PayrollProcessingProgress,它的主键是另一个表的值,PayrollPeriod。它不是一对一的映射,因为PayrollPeriod有1个或零个PayrollProcessingProgresses。

我的映射

public class PayrollProcessingProgressMap : ClassMap<PayrollProcessingProgress>
{
public PayrollProcessingProgressMap()
{
    Table("PayrollProcessingProgress");

     Id(x => x.PayrollPeriodId).GeneratedBy.Foreign("PayrollPeriodId");

    Map(x => x.RecordsProcessed);
}
}

表格

CREATE TABLE [dbo].[PayrollProcessingProgress](
    [PayrollPeriodId] [uniqueidentifier] NOT NULL,
    [RecordsProcessed] [int] NOT NULL,
 CONSTRAINT [PK_PayrollProcessingProgress] PRIMARY KEY CLUSTERED 
(
    [PayrollPeriodId] ASC
)
)

GO

ALTER TABLE [dbo].[PayrollProcessingProgress]  WITH CHECK ADD  CONSTRAINT [FK_PayrollProcessingProgress_PayrollPeriods] FOREIGN KEY([PayrollPeriodId])
REFERENCES [dbo].[PayrollPeriods] ([Id])
GO

ALTER TABLE [dbo].[PayrollProcessingProgress] CHECK CONSTRAINT [FK_PayrollProcessingProgress_PayrollPeriods]
GO

我可以阅读&lt;&gt;并成功更新我在db中手动保存的实体上的数字字段,但是当我尝试

Save(new PayrollProcessingProgress{
PayrollPeriodId = [Guid I know to be a valid payrollperiodid],
RecordsProcessed = 0
}

我得到“无法解析财产:PayrollPeriodId”

1 个答案:

答案 0 :(得分:1)

您必须定义对主实体的引用以使用Id或将其定义为简单的关键引用

public PayrollProcessingProgress
{
    public virtual PayrollPeriod Period { get; set; }
    public virtual int RecordsProcessed { get; set; }
}

public PayrollProcessingProgressMap()
{
    CompositeId().KeyReference(x => x.Period, "PayrollPeriodId");

    Map(x => x.RecordsProcessed);
}

另一种可能性是在主类ans使用连接映射中将其映射为可空属性。但是,您无法再删除RecordsProcessed记录

public PayrollPeriod
{
    ...
    public virtual int? RecordsProcessed { get; set; }
}

public PayrollPeriodMap()
{
    Join("PayrollProcessingProgress", join => 
    {
        join.KeyColumn("PayrollPeriodId");
        join.Optional();
        join.Map(x => x.RecordsProcessed);
    });
}