实体框架。添加新记录并仅通过一个查询返回总记录

时间:2018-11-22 09:10:24

标签: c# entity-framework-6

我正在使用Entity Framework 6,并且有一种方法可以将对象添加到用户收藏夹中。我需要添加一个对象,然后在所有用户的收藏夹中返回该元素的总添加量:

public class FavoritesRepository : BaseRepository
{
     public async Task<Favorites> AddAsync(Favorites favorites)
     {
       _context.Add(favorites);
       await _context.SaveChangesAsync();

       return favorites;
    }
}


public class FavoritesService
{
   public async Task<AddFavoritesElementOperationResultModel> AddAsync(ObjectType objectType, long objectId)
   {
      //Some business logic
      favorites = new Favorites
      {
         ObjectTypeId = objectTypeId,
         ObjectId = objectId,
         AuthorUserId = currentUserId
       };
       favorites = await _favoritesRepository.AddAsync(favorites);

       long total = await _favoritesRepository.GetFavoritesElementCountAsync(objectTypeId, objectId);
       return new AddFavoritesElementOperationResultModel
       {
          Id = favorites.Id,
          ObjectTypeId = objectTypeId,
          ObjectId = objectId,
          Total = total
       };
    }
}

是否可以通过在插入时仅执行一次查询来添加和返回此元素的添加总数,即不调用GetFavoritesElementCountAsync(..)?

0 个答案:

没有答案