从另一个更新一个DataTable

时间:2011-01-27 09:32:46

标签: linq datatable

create table employee
(
    id int,
    name varchar(10),
    dept_id int,
    dept_name varchar(10)
);

insert into employee values(1, 'ABC1', 1, '');
insert into employee values(2, 'ABC2', 2, '');
insert into employee values(3, 'ABC3', 1, '');
insert into employee values(4, 'ABC4', 2, '');
insert into employee values(5, 'ABC5', 1, '');

create table dept
(
    dept_id int,
    dept_name varchar(10)
);

insert into dept values(1, 'XYZ1');
insert into dept values(2, 'XYZ2');
UPDATE e
SET    e.dept_name = d.dept_name
FROM   employee AS e
       JOIN dept AS d
       ON e.dept_id = d.dept_id

如何将上述查询(粗体字母)转换为LINQ查询?

3 个答案:

答案 0 :(得分:0)

我不确定你能不能。 Linq to SQL意味着将数据输入/输出数据库以便在应用程序代码中使用。你想要的是一个较低级别的数据操作,最好在T-SQL中完成,如你的例子所示。

您可以使用连接将两个表中的记录加载到另一个对象中,然后迭代结果。

// I'm doing this this way because I can't remember the syntax for 
// LoadOptions and want to be sure to avoid the SELECT N+1 issue.
var query = from e in db.Employees
            select new EmployeeDepartment
                       {
                           Employee = e,
                           Department = e.Department
                       };

foreach (var item in query)
{
    item.Employee.DepartmentName = item.Department.DepartmentName;
}

db.SubmitChanges();

<强>然而
您可能已经知道这一点,但最好规范化您的数据库,以便部门名称上的部门名称仅 ,并使用您的employee-&gt;部门关系获取部门名称给定的员工。

答案 1 :(得分:0)

使用join

var employeeDept = from e in db.employees 
                  Join d in db.Depts on e.dept_id equals d.dept_id 
                  select new 
                  {Employee = e ,
                   Department = d};

foreach(var ed in employeeDept)
{
   ed.Employee.DepartmentName = ed.Department.DepartmentName;
}
db.submitChanges();

答案 2 :(得分:0)

其中一个解决方案如下:

var enumEmp = employee.AsEnumerable(); 
var enumDept = dept.AsEnumerable();

var employeeDept = from empl in enumEmp 
join d in enumDept on empl.Field<int>("dept_id") equals d.Field<int>("dept_id")
select new {enumEmp = empl , enumDept = d};

foreach(var ed in employeeDept)
{
ed.enumEmp.SetField<string>("dept_name",ed.enumDept.Field<string>("dept_name"));
}