我有这个我要翻译成实体框架的SQL查询
我需要在实体的一次运行中插入多行,就像这个查询所做的那样
INSERT INTO dbo.tbllistDepartment
(
department_sys_id,
department,
status,
client_sys_id,
lang_sys_id
)
SELECT @siDepartmentSysId,@siDepartment, @iiStatus,
@siClientSysId, lang_sys_id
FROM tblLanguageSettings
WHERE lang_sys_id <> 'Admin001'
我试过这个,但只插了一行
public static void Insert(string langSysId, string clientSysId,string name, int status)
{
Crs2Model context = new Crs2Model();
string SysId = MyLibrary.StringCreator.GetSysId();
tblListDepartment deptObj = new tblListDepartment()
{
department_sys_id = SysId,
client_sys_id = clientSysId,
lang_sys_id=langSysId,
department=name,
status=status
};
context.tblListDepartments.Add(deptObj);
context.SaveChanges();
}
答案 0 :(得分:2)
首先,您需要来自tbllistDepartment表的过滤数据。然后循环遍历这些数据。 这是一个例子。你可以参考,我的朋友:
using (DBContext ctx = new DBContext())
{
var department = ctx.tbllistDepartment.Where(c => c.lang_sys_id != "Admin001");
foreach(var item in department)
{
var obj = new tbllistDepartment()
{
department_sys_id = item.department_sys_id,
department = item.department,
status = item.status,
client_sys_id = item.client_sys_id,
lang_sys_id = item.lang_sys_id
}
ctx.tbllistDepartment.Add(obj);
}
// Insert into the database.
ctx.SaveChanges();
}
答案 1 :(得分:2)
添加您的课程:
using Microsoft.EntityFrameworkCore;
您可以使用命令
_context.Database.ExecuteSQLCommand (sqlcommand,[parameters]);
这些是以下命令:
string sqlCommand = "INSERT INTO dbo.tbllistDepartment (department_sys_id,department,status,client_sys_id,lang_sys_id) SELECT {0},{1},{2}, {3},{4} FROM tblLanguageSettings WHERE lang_sys_id <> {5}";
_context.Database.ExecuteSqlCommand(sqlCommand, @siDepartmentSysId,@siDepartment,@iiStatus, @siClientSysId, lang_sys_id,'Admin001');