我的代码优先实体框架应用程序中存在一个奇怪的问题。通常情况下,如果我有以下代码,我可以在ajax中正确地附加一个具有CommentsAssociated的特定帖子。
gEchoLuDBContext db = new gEchoLuDBContext();
var post= db.Posts.Include(po=>po.CommentsAssociated).Include(po => po.Person)
.Single(p => p.PostId == postId)
.AsNoTracking();
但是,如果我使用以下代码(我必须这样做),我在ajax中没有得到CommentAssociated的值。
gEchoLuDBContext db = new gEchoLuDBContext();
IEnumerable<Post> post = db.Posts.Where(p => p.PostId == postId)
.Include(p => p.Person)
.Include(p => p.CommentsAssociated)
.Include(p => p.PostBookmarks)
.Include(p => p.PostLikes)
.ToList().Select(p => new Post
{
PostId = p.PostId,
Title = p.Title,
Content = p.Content,
DatePosted = p.DatePosted,
Person = p.Person,
CommentsAssociated = p.CommentsAssociated,
IsLikedByCurrentUser = p.PostLikes.Select(pl => pl.UserId).Contains(User.Identity.GetUserId()),
IsBookmarkedByCurrentUser = p.PostBookmarks.Select(pb => pb.BookmarkedBy).Contains(User.Identity.GetUserId()),
NoOfComments = p.CommentsAssociated.Count()
});
var returnpost = post.FirstOrDefault();
return returnpost;
在这两种情况下,我在VS调试模式下都有有效的CommentsAssociated。但是,我只是无法在ajax中获得CommentAssociated,它在ajax中没有任何价值。以下是Post类的相关部分:
public class Post
{
public int PostId { get; set; }
public List<Comment> CommentsAssociated { get; set; }
}
以下是Ajax代码的相关部分:
$.ajax({
url: '/api/post/GetPostWithFullDetails?postId=' + postId,
type: 'GET',
contentType: "application/json; charset=utf-8;",
dataType: 'json',
success: function (post) {
$("#pnl_DisplayPostDetails.posttitle").html(post.Title);
$("#pnl_DisplayPostDetails.postcontent").html(post.Content);
if (post.CommentsAssociated.length) {
//other code
UPDATE 当我在控制器中序列化post对象并返回它时:
string json = JsonConvert.SerializeObject(post, Formatting.Indented, serializerSettings);
我仍然遇到与json字符串格式相同的问题,如下图所示: