FluentNhibernate和HasMany

时间:2012-09-02 12:41:50

标签: fluent-nhibernate fluent-nhibernate-mapping

我尝试使用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?因为我过滤的文件属于那个用户。

1 个答案:

答案 0 :(得分:1)

看起来您需要在子集合OwnedDocuments

上设置级联选项
this.HasMany(x => x.OwnedDocuments).Inverse().Cascade.AllDeleteOrphan();

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

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