我有一个关于 LINQ 删除的问题。我的数据库中有 2 个表,它们已连接起来。
第一个表:empid
、empname
、salary
、dname
第二个表:dId
,dname
我想从第一个表中删除一名员工,并从子表中删除所有引用。我为此编写了以下代码,查询执行后表保持相同状态。如何使用 LINQ 删除它?请解释需要进行哪些更改才能获得正确的解决方案。
public string DeleteData(int id)
{
try
{
var emplist = new List<ViewDetails>();
// tble_dept dept = new tble_dept();
//tble_Emp emp = new tble_Emp();
OperationDataDataContext dc = new OperationDataDataContext();
var employess = from emps in dc.tble_Emps
join depts in dc.tble_depts
on emps.deptid equals depts.id
select new ViewDetails
{
empid = emps.EmpId,
empname = emps.EmpName,
salary = emps.EmpSalary,
dname = depts.Dname,
};
var company = employess.FirstOrDefault(c => c.empid == id);
emplist = employess.ToList();
if (company == null)
return "Company cannot be found";
emplist.Remove(company);
dc.SubmitChanges();
return "ok";
}
catch (Exception ex)
{
return ex.Message;
}
}
最佳答案
public string DeleteData(int id)
{
try
{
var emplist = new List<ViewDetails>();
// tble_dept dept = new tble_dept();
//tble_Emp emp = new tble_Emp();
OperationDataDataContext dc = new OperationDataDataContext();
int q = Convert.ToInt32(id);
var employess = from emps in dc.tble_Emps
join depts in dc.tble_depts
on emps.deptid equals depts.id
where q == emps.EmpId
select emps;
// if (company == null)
// return "Company cannot be found";
dc.tble_Emps.DeleteAllOnSubmit(employess);
dc.SubmitChanges();
return "ok";
}
catch (Exception ex)
{
return ex.Message;
}
}
关于c# - LINQ Join从多个表中删除内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29073597/