0

我用 FluentNhibernate 尝试了一个简单的测试应用程序,但它没有按我的预期工作。这是我的课程:

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

第一个问题是,为什么我不调用document.Add(list);时文档计数总是0?我想当我将一些文档添加到用户的文档集合中时,它们会自动添加到文档中吗?为什么最后一个测试是 100?因为我过滤了属于该用户的文档。

4

1 回答 1

1

看起来您需要在子集合上设置级联选项OwnedDocuments

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

如果您将任何子对象添加到集合中,上述设置将保存所有子对象,如果您从集合中删除它们并保存对象,它将删除这些子对象。您可以在 nhibernate 文档中找到有关这些设置的更多信息:

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

于 2012-09-02T15:20:14.773 回答