将实体添加到存储库时发生异常
将帖子添加到帖子存储库时,会出现异常并显示以下消息:not null property引用了 null 或瞬态值 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);
}
}
谢谢!
While adding post to the post repository an exception occurs with the following message: 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);
}
What does it mean?
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);
}
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
抛出该异常是因为 NHibernate 尝试添加对未保留在数据库中的类别的引用。在您的示例中,您正在创建一个新类别,因此您有两个选择:
对于第二个选项,如果您使用 Xml 映射,那么您将需要类似的内容:
如果您使用 Fluent NHibernate,那么它将是:
That exception was thrown because NHibernate tried to add a reference to a Category that was not persisted on the database. In you example you are creating a new Category, so you have two options:
For the second option, if you are using Xml mapping, then you'll need something like:
If you are using Fluent NHibernate, then it'll be: