Home > Software engineering >  Delete Rows from multiple tables using Linq web Api asp.net
Delete Rows from multiple tables using Linq web Api asp.net

Time:01-04

public async Task<IHttpActionResult> DeleteUser(string id)
        {
            try {
                using (hospiceEntities db = new hospiceEntities())
                {
                    Guid guid_id = Guid.Parse(id);
                    var q =
                    (from user in db.Users
                     join resource in db.Resources
                     on user.Id equals resource.UserId
                     where user.Id == guid_id
                     select user).Single<User>();

                    foreach (Resource res in q.Resources)
                    {
                        db.Resources.Remove(res);

                    }
                    db.Users.Remove(q);
                    await db.SaveChangesAsync();
                    return Ok(Helper.SuccessResponse("User Deleted"));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

I have two tables Users and Resource that are connected through foreign key constraint. I have written the above LINQ query to delete the record but its not deleting it. Please tell what i am doing wrong in it. Thanks

CodePudding user response:

Try to include resources using this syntax

    var user = await
    db.Users
   .Include(u=>u.Resources)
   .Where(u=> u.Id == guid_id)
   .FirstOrDefaltAsync();

   var res=user.Resources.ToList();
     db.Resources.RemoveRange(res);

    // or try directly
   db.Resources.RemoveRange(user.Resourses);

  //or maybe this is better
     user.Resources==null;
     
     db.Users.Remove(user);
     await db.SaveChangesAsync();
  

CodePudding user response:

use this in foreach loop

(db.GetTable<Resource>().DeleteOnSubmit(res));

and use this code

db.GetTable<Users>().DeleteOnSubmit(q);  
                    db.SubmitChanges();  

instead of (db.Users.Remove(q));

  • Related