向存储库添加实体时发生异常
本文关键字:异常 实体 存储 添加 | 更新日期: 2023-09-27 18:18:51
在向post存储库添加post时,出现以下异常消息: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);
}
这是什么意思?
EDIT: Post entity definition
[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);
}
}
谢谢!
这个异常被抛出是因为NHibernate试图添加一个没有在数据库上持久化的Category的引用。在您的示例中,您正在创建一个新的类别,因此您有两个选项:
- 保存文章前先保存类别;
- 更改Post映射并使其级联保存关联;
<many-to-one name="Category" column="CategoryId" cascade="all"/>
如果你正在使用Fluent NHibernate,那么它将是:
References(x => x.Category, "CategoryId").Cascade.All();