2013-04-10 50 views
1

鑑於以下模型,我希望能夠輸入新的WriteOffApprovalUser並使Employee字段爲空。這是1:1或null關係。流利的NHibernate - 1:1與可空字段的關係

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爲空。我如何指定該員工可以爲空?

此外,所有Id字段必須是整數?我們桌子上的很多按鍵都是字符串。

回答

-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(); 
+0

OK,但真正發生的是有一個'僱主'已經和我只想進入'WriteOffApprovalUser',然後當我查詢關係的時候。我不想添加「員工」一側,但總是隻有一個「員工」到一個「WriteOffApprovalUser」,反之亦然。合理? – Sam 2013-04-10 15:34:54

+0

我得到這個錯誤:''FluentNHibernate.Mapping.OneToOnePart '不包含'Nullable'的定義,也沒有接受'FluentNHibernate'類型的第一個參數的擴展方法'Nullable'。可以找到Mapping.OneToOnePart (您是否缺少使用指令或程序集引用?)' – Sam 2013-04-10 15:37:08

+0

您的意思是延遲加載?對於性能問題或設計你不需要這個'實體' – IamStalker 2013-04-10 15:37:10