延迟加载和RequiredAttribute问题:XXX字段为必填项
我有一个 Comment
类,其中包含一个 Author
属性:
public class Comment : IEquatable<Comment>
{
public int ID { get; set; }
[Required]
public virtual User Author { get; set; }
// More properties here
}
我希望用户能够“喜欢”评论,就像 StackOverflow 上的那样。为此,我在 CommentController
中执行了以下操作:
public virtual ActionResult Like(int id)
{
var comment = _session.Single<Comment>(c => c.ID == id);
comment.Likes++;
_session.CommitChanges();
return Json(new { comment.Likes });
}
每当我调用此操作时,我都会收到以下验证错误:
作者字段为必填项。
Comment
对象来自数据库,因此它有一个作者。 “有趣”的是,每当我使用 Visual Studio 调试器检查 Author
是否确实丢失时,验证错误都不会触发。
我在这里假设问题是 Author
属性从未发生延迟加载是否正确?如果是这样,仅针对这种情况,我如何强制填写所有导航属性? (否则我想继续使用延迟加载)
解决这个问题的最巧妙的方法是什么?我是否走在正确的轨道上? 为什么 EF 明确要求它保存实体时却没有发生延迟加载?
任何帮助将不胜感激。
I have a Comment
class with, among others, an Author
property:
public class Comment : IEquatable<Comment>
{
public int ID { get; set; }
[Required]
public virtual User Author { get; set; }
// More properties here
}
I want users to be able to "like" a comment, much like here at StackOverflow. To that end I have the following action in my CommentController
:
public virtual ActionResult Like(int id)
{
var comment = _session.Single<Comment>(c => c.ID == id);
comment.Likes++;
_session.CommitChanges();
return Json(new { comment.Likes });
}
Whenever I invoke this action I get the following Validation Error:
The Author field is required.
The Comment
object comes from the db, so it does have an author. The "funny" thing is, whenever I use the Visual Studio debugger to check whether the Author
really is missing, the validation error does not fire.
Am I correct in assuming here that the problem is that the lazy loading of the Author
property never takes place? If so, how can I, for this situation only, force all navigation properties to be filled in? (I want to keep working with lazy loading otherwise)
What's the neatest way to solve this? Am I even on the right track?
And why isn't lazy loading happening while EF clearly requires it to save the entity?
Any help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
包含
以急切地获取数据上下文上的关系。You could use
Include
to eagerly fetch a relation on the data context.我也遇到过类似的问题。下面的内容应该可以工作(启用 LazyLoading)。
I have had a similar problem. The below should work (with LazyLoading enabled).