开发者

Lazy Loading and RequiredAttribute problem: The XXX field is required

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.


You could use Include to eagerly fetch a relation on the data context.

context.Comments.Include("Author").Single<Comment>(c => c.ID == id);


I have had a similar problem. The below should work (with LazyLoading enabled).

public virtual ActionResult Like(int id)
{

   var comment = _session.Single<Comment>(c => c.ID == id);
   comment.Likes++;

   if(TryUpdateModel(comment))
   {

       _session.CommitChanges();

   }
   return Json(new { comment.Likes });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜