我对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;
}
}
答案 0 :(得分:1)
您应该使用DeleteAllOnSubmit
var company = employess.FirstOrDefault(c => c.empid == id);
if (company == null)
return "Company cannot be found";
dc.tble_Emps.DeleteAllOnSubmit(company);
dc.SubmitChanges();
return "ok";
答案 1 :(得分:1)
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;
}
}
答案 2 :(得分:0)
级联删除功能。如果父表与子表具有一对多的关系。删除父表行时,将删除子行或将外键列设置为null。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasOptional<Standard>(s => s.Standard)
.WithMany()
.WillCascadeOnDelete(false);
}
有关Cascade on Delete的详细信息,请参阅此链接:http://www.entityframeworktutorial.net/code-first/cascade-delete-in-code-first.aspx