2012-09-02 73 views
0

我嘗試一個簡單的測試應用程序與FluentNhibernate,但它不工作,因爲我的預期。 這裏是我的課:FluentNhibernate和HasMany

public class Document : DataEntity 
{ 
    public virtual string Title { get; set; } 

    public virtual string FileName { get; set; } 

    public virtual DateTime LastModificationDate { get; set; } 

    public virtual User LastModificationBy { get; set; } 

    public virtual byte[] Content { get; set; } 

    public virtual User Owner { get; set; } 
} 

public class User : DataEntity 
{ 
    public virtual string FirstName { get; set; } 

    public virtual string LastName { get; set; } 

    public virtual string Login { get; set; } 

    public virtual string PasswordHash { get; set; } 

    public virtual string Email { get; set; } 

    public virtual IList<Document> OwnedDocuments { get; set; } 

    public User() 
    { 
     this.OwnedDocuments = new List<Document>(); 
    } 
} 

internal class UserMapping : ClassMap<User> 
{ 
    public UserMapping() 
    { 
     this.Id(x => x.Id); 
     this.Map(x => x.FirstName); 
     this.Map(x => x.LastName); 
     this.HasMany(x => x.OwnedDocuments).Inverse(); 
    } 
} 

    public DocumentMapping() 
    { 
     this.Id(x => x.Id); 
     this.Map(x => x.Title); 
     this.Map(x => x.FileName).Not.Nullable(); 
     this.Map(x => x.LastModificationDate).Index("IDX_ModificationDate"); 
     this.Map(x => x.Content); 
     this.References(x => x.LastModificationBy).Column("LastModificationBy"); 
     this.References(x => x.Owner).Column("Owner"); 
     this.Table("Document"); 
    } 

我嘗試用下面的代碼

using (var transaction = Session.BeginTransaction()) 
     { 
      var users = this.kernel.Get<IRepository<User>>(); 
      var document = this.kernel.Get<IRepository<Document>>(); 
      var user = new User { Login = "Blubb" }; 
      users.Add(user); 
      var list = Builder<Document>.CreateListOfSize(50).All().With(x => x.Owner = user).Build().ToList(); 
      var list2 = Builder<Document>.CreateListOfSize(50).All().Build().ToList(); 
      list.ForEach(x => user.OwnedDocuments.Add(x)); 
      document.Add(list); 
      document.Add(list2); 
      transaction.Commit(); 
      var i = document.All().Count(); 
      i.Should().Be(50); 
      var docs = ((IGuidKeyedRepository<User>)users).FindBy(user.Id).OwnedDocuments.Count(); 
      docs.Should().Be(50); 
     } 

的第一個問題就是測試它,爲什麼是文檔計數始終爲0的時候,我不叫document.Add(名單);?當我向用戶的文檔集合添加一些文檔時,他們會自動添加到文檔中? 爲什麼最後一次測試100?因爲我過濾了屬於該用戶的文檔。

回答

1

看起來你需要設置子集的級聯選項OwnedDocuments

this.HasMany(x => x.OwnedDocuments).Inverse().Cascade.AllDeleteOrphan(); 

上面的設置會保存所有的孩子,如果你添加任何的集合,如果你從集合中刪除,並保存該對象將刪除這些子對象。您可以在nhibernate文檔中找到有關這些設置的更多信息:

http://www.nhforge.org/doc/nh/en/