将实体添加到存储库时发生异常

时间:2011-12-28 10:31:15

标签: c# unit-testing nhibernate entity

将帖子添加到帖子库时,会发生以下消息的异常:not null property references a null or transient value Category

[Test]
public void PostInsertion()
{
    var category = new Category 
    {
        Title = "Programming",
        Description = "Programming"
    };
    var post = new Post
    {
        AuthorUrl = "some url",
        Category = category,
        Content = "some content",
        Feedbacks = new HashedSet<Feedback>(),
        Timestamp = DateTime.Now,
        Title = "some title"
    };

    var postRepository = new Repository<Post>(this.sessionFactory);
    postRepository.Add(post);
}

这是什么意思?

编辑:发布实体定义

[Serializable]
public class Post : Entity<Post>
{
    public Post()
    {
        this.Feedbacks = new HashedSet<Feedback>();
    }

    public virtual String Title { get; set; }
    public virtual String Content { get; set; }
    public virtual DateTime Timestamp { get; set; }
    public virtual Byte[] Thumbnail { get; set; }
    public virtual Byte[] AuthorImg { get; set; }
    public virtual String AuthorUrl { get; set; }
    public virtual Category Category { get; set; }
    public virtual ISet<Feedback> Feedbacks { get; set; }

    public virtual void AddFeedback(Feedback feedback)
    {
        this.Feedbacks.Add(feedback);
    }
}

谢谢!

1 个答案:

答案 0 :(得分:3)

抛出该异常是因为NHibernate试图添加对数据库中未持久存在的类别的引用。在您的示例中,您正在创建一个新类别,因此您有两个选项:

  1. 保存帖子之前保存类别;
  2. 更改帖子映射并使其级联保存关联;
  3. 对于第二个选项,如果您使用的是Xml映射,那么您需要以下内容:

    <many-to-one name="Category" column="CategoryId" cascade="all"/>
    

    如果您使用的是Fluent NHibernate,那么它将是:

    References(x => x.Category, "CategoryId").Cascade.All();