Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# EF Core-在不加载实体的情况下修改实现_C#_Entity Framework_Entity Framework Core - Fatal编程技术网

C# EF Core-在不加载实体的情况下修改实现

C# EF Core-在不加载实体的情况下修改实现,c#,entity-framework,entity-framework-core,C#,Entity Framework,Entity Framework Core,我试图实现一个功能,让用户喜欢评论。如果用户已经喜欢它,就不能再喜欢它,反之亦然。 这就是它看起来的样子: public async Task<ActionResult<CommentResponse>> LikeComment(LikeComment like) { if (like.HasNullProperty()) return BadRequest("Missing properties!&quo

我试图实现一个功能,让用户喜欢评论。如果用户已经喜欢它,就不能再喜欢它,反之亦然。 这就是它看起来的样子:

    public async Task<ActionResult<CommentResponse>> LikeComment(LikeComment like)
    {
        if (like.HasNullProperty())
            return BadRequest("Missing properties!");
        var comment = await commentService.GetCommentWithLikes((int) like.CommentId);
        if(comment is null)
            return NotFound($"No comment with id {like.CommentId} was found");
        try
        {
            var userId = User.GetUserID();
            comment = await commentService.LikeComment(comment, userId, (bool)like.Liked);
            return comment is not null ? Ok(comment.GetCommentResponse((bool)like.Liked)) : StatusCode(304);
        }
        catch(Exception e)
        {
            return StatusCode(500, $"Error while trying to {((bool)like.Liked ? "like" : "dislike")} comment");
        }
    }
公共异步任务

这是一个不喜欢时(只有diff是like计数…):

就在失败之前:

也许有人知道这种行为的原因,可以帮助我或建议一种不同的方法:) 谢谢

在GetCommentsWithLikes函数中使用.AsNoTracking()没有帮助

由于使用了投影,该函数已经隐式没有跟踪。这是下面的电话

var hasLiked = await blogContext.Comments
    .Where(x => x.Id == comment.Id && x.LikedBy.Any(x => x.Id == user.Id))
    .FirstOrDefaultAsync() is not null;
当结果不为空时,它将
注释
实例添加到更改跟踪器

由于您不需要该实例,并且只是检查是否存在,因此请使用以下方法,该方法不涉及实体实例,而是纯服务器端查询:

var hasLiked = await blogContext.Comments
    .AnyAsync(x => x.Id == comment.Id && x.LikedBy.Any(x => x.Id == user.Id));

哦,真的很简单。。。谢谢^^
var hasLiked = await blogContext.Comments
    .Where(x => x.Id == comment.Id && x.LikedBy.Any(x => x.Id == user.Id))
    .FirstOrDefaultAsync() is not null;
var hasLiked = await blogContext.Comments
    .AnyAsync(x => x.Id == comment.Id && x.LikedBy.Any(x => x.Id == user.Id));