How to delete a single row from database using linq query?

拈花ヽ惹草 提交于 2020-01-06 01:56:07

问题


This is my table ts_grp_perm_mapping

grp_permid     grp_id      perm_id
22              4           1
23              2           2

This is my code to delete row. usr_groupId below is grp_id in above table. usr_doctypeids below is perm_id in above table.

public int saveNewUser(int usr_groupId, int usr_doctypeids)
{
     ts_grp_perm_mapping tm = db.ts_grp_perm_mapping.Find(usr_groupId);
     db.ts_grp_perm_mapping.Remove(tm);
     int rowiseffected=db.SaveChanges();
     return rowiseffected;
}

When I trace my tm shows null, and error pops up like values cannot be null. So where I am going wrong?


回答1:


If grp_id is Primary Key

 public int saveNewUser(int usr_groupId, int usr_doctypeids)
    {
         ts_grp_perm_mapping tm = db.ts_grp_perm_mapping.SingleOrDefault(ts => ts.grp_id == usr_groupId);
         if(tm != null)
             {
         db.ts_grp_perm_mapping.Remove(tm);
         int rowiseffected=db.SaveChanges();
         return rowiseffected;
    }
    else
    {
    return 0;
    }
    }

If grp_id is not a primary key

public int saveNewUser(int usr_groupId, int usr_doctypeids)
        {
             ts_grp_perm_mapping tm = db.ts_grp_perm_mapping.FirstOrDefault(ts => ts.grp_id == usr_groupId);
             if(tm != null)
                 {
             db.ts_grp_perm_mapping.Remove(tm);
             int rowiseffected=db.SaveChanges();
             return rowiseffected;
        }
        else
        {
        return 0;
        }
        }



回答2:


Find only works for the Primary Key. Use Linq Single or SingleOrDefault for other properties.

public int saveNewUser(int usr_groupId, int usr_doctypeids)
{
     ts_grp_perm_mapping tm = db.ts_grp_perm_mapping.SingleOrDefault(ts => ts.grp_id == usr_groupId);
     if(tm == null)
         throw new Exception($"The grp_id {usr_groupId} was not found");
     db.ts_grp_perm_mapping.Remove(tm);
     int rowiseffected=db.SaveChanges();
     return rowiseffected;
}

And if possible make your method async and use

ts_grp_perm_mapping tm = await db.ts_grp_perm_mapping.SingleOrDefaultAsync(ts => ts.grp_id == usr_groupId).ConfigureAwait(false);
//...
int rowiseffected = await db.SaveChangesAsync().ConfigureAwait(false);



回答3:


Try

        public int saveNewUser(int usr_groupId, int usr_doctypeids) 
    { 
      var tm = db.ts_grp_perm_mapping.Where(a => a.grp_id == usr_groupId); 
      db.ts_grp_perm_mapping.Remove(tm); 
      int rowiseffected=db.SaveChanges();
      return rowiseffected;
    }


来源:https://stackoverflow.com/questions/35172596/how-to-delete-a-single-row-from-database-using-linq-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!