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);
}
}
我有两个通过外键约束连接的表用户和资源。我已经撰写了上面的 LINQ 查询来洗掉记录,但它没有洗掉它。请告诉我我做错了什么。谢谢
uj5u.com热心网友回复:
尝试使用此语法包含资源
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();
uj5u.com热心网友回复:
在 foreach 回圈中使用它
(db.GetTable<Resource>().DeleteOnSubmit(res));
并使用此代码
db.GetTable<Users>().DeleteOnSubmit(q);
db.SubmitChanges();
代替 (db.Users.Remove(q));
uj5u.com热心网友回复:
以这种方式解决它:
public async Task<IHttpActionResult> DeleteUser(string id)
{
try {
using (hospiceEntities db = new hospiceEntities())
{
Guid guid_id = Guid.Parse(id);
var deleteuser = db.Users.FirstOrDefault(e => e.Id == guid_id);
if (deleteuser == null)
{
return Content(HttpStatusCode.NotFound, "User Not Found");
}
else
{
var q =
from user in db.Users
join resource in db.Resources
on user.Id equals resource.UserId
where user.Id == guid_id
select new
{
Users = user,
Resources = resource
};
foreach (var item in q)
{
db.Resources.Remove(item.Resources);
db.Users.Remove(item.Users);
}
await db.SaveChangesAsync();
}
}
return Ok(Helper.SuccessResponse("User Deleted"));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
0 评论