流利的NHibernate - 与Nullable Field的1:1关系

时间:2013-04-10 15:18:50

标签: nhibernate fluent-nhibernate

鉴于以下模型,我希望能够输入新的WriteOffApprovalUser并使Employee字段为空。这是1:1或null关系。

public class WriteOffApprovalUser
{
    public virtual string UserName { get; set; }
    public virtual Employee Employee { get; set; }
}

public class Employee
{
    public virtual string EmployeeID { get; set; }
    public virtual string EmployeeStatusCode { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string JobTitle { get; set; }
    public virtual string Division { get; set; }
    public virtual string Department { get; set; }
    public virtual string Location { get; set; }
    public virtual string City { get; set; }
    public virtual string DeskLocation { get; set; }
    public virtual string MailID { get; set; }
    public virtual string Phone { get; set; }
    public virtual string PreferredName { get; set; }
    public virtual string Fax { get; set; }
    public virtual string SecCode { get; set; }
    public virtual string SupervisorID { get; set; }
    public virtual string UserId { get; set; }
}

类地图

public class WriteOffApprovalUserMap : ClassMap<WriteOffApprovalUser>
{
    public WriteOffApprovalUserMap()
    {
        Table("WRITEOFF_APPROVAL_USER");

        Id(x => x.UserName).Column("USER_NAME");

        //Map(x => x.Employee).Nullable();

        HasOne(x => x.Employee)
            .Class<Employee>()
            .Constrained()
            .Cascade.SaveUpdate()
            .PropertyRef("UserId");
    }
}

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        Table("ADP_EMPLOYEE");

        Id(x => x.EmployeeID).Column("EMPLID").GeneratedBy.Native("");

        Map(x => x.FirstName).Column("FIRST_NAME");
        Map(x => x.LastName).Column("LAST_NAME");
        Map(x => x.PreferredName).Column("PREFERRED_NAME");
        Map(x => x.UserId).Column("USER_ID");
    }
}

查询/保存

using (var session = SessionProvider.GetSession())
        {
            using (var tx = session.BeginTransaction())
            {
                var user = new WriteOffApprovalUser() { UserName = "SAMSTR" };

                session.Save(user);

                tx.Commit();
            }
        }

这抱怨Employee为空。如何指定Employee可以为null?

此外,所有Id字段都必须是整数吗?我们表上的很多键都是字符串。

1 个答案:

答案 0 :(得分:-1)

首先,如果你把它设置为1:1它不应该是NULL,因为它不是正确的设计。

但这是一个如何操作的例子:

1)单程

HasOne(x => x.Employee)
            .Class<Employee>().Nullable().NotFound.Ignore().PropertyRef("UserId");

2)第二种方式

References(x => x.Category).Column("UserId").Nullable().NotFound.Ignore();