skip to Main Content

Below is the object

namespace TestingForCw2.Shared
{
   public class Dog
   {
       [Key]
       public Int32 Id { get; set; }
       public string DogName { get; set; }
       public Int32 DogAge { get; set; }
   }
}

This is the code for updating a Dog object in asyncrnous,

        public async Task<bool> UpdateDog(Dog dog)
        {
            try
            {
                await _appDbContext.Dog.Where(d => d.Id == dog.Id).UpdateAsync(d => new Dog
                {
                    DogName = dog.DogName
                    , DogAge = dog.DogAge
                });

                return true;
            }
            catch(Exception exception)
            {
                return false;
            }
        }

Although for some reason i get the following error

Error : The query must be of type ObjectQuery or DbQuery. (Parameter ‘source’)

Hope someone can help me to fix this, thank you!

2

Answers


  1. Chosen as BEST ANSWER
            public async Task<bool> UpdateDog(Dog dog)
            {
                Dog dogToUpdate = await _appDbContext.Dog.FindAsync(dog.Id);
                dogToUpdate.DogName = dog.DogName;
                dogToUpdate.DogAge = dog.DogAge;
                try
                {
                    await _appDbContext.SaveChangesAsync();
                    return true;
                }
                catch (Exception exception)
                {
                    return false;
                }
            }
    

    With the help of @JackZanardo logic, i basically removed the 'UpdateAsync' await line, and used FindAsync method.


  2. My guess would be that it is because you’re try to both query _appDbContext.Dog and update it at the same time.
    My approach would be to first pull up the entity that I’m trying to change, change its props and then update it.

        public async Task<bool> UpdateDog(Dog dog)
        {
            Dog dogToUpdate = await _appDbContext.Dog.FirstOrDefaultAsync(d => d.Id == dog.Id);
            dogToUpdate.DogName = dog.DogName;
            dogToUpdate.DogAge = dog.DogAge;
            try
            {
                await _appDbContext.Dog.UpdateAsync(dogToUpdate);
                await _appDbContext.SaveChangesAsync();
                return true;
            }
            catch(Exception exception)
            {
                return false;
            }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search