[英]Checking for duplicates before updating with dapper linq c#
I'm relatively new to Linq and Dapper and I'm trying to find the most effecient way to make an insert happen. 我对Linq和Dapper还是比较陌生,我正在尝试找到最有效的方法来实现插入。 I have a list object that looks like this:
我有一个看起来像这样的列表对象:
public class Programs
{
public int Id { get;set; }
public int Desc { get;set; }
}
The list object is populated from a string field on the page which typically contains a string of Id's (eg 234, 342, 345, 398). 列表对象是从页面上的字符串字段填充的,该字段通常包含一串Id(例如234、342、345、398)。 Now in the database 234, 342, 345 already exist so the only one that I really need to insert is 398 along with the record Id.
现在在数据库234、342、345中已经存在,因此我真正需要插入的唯一一个是398和记录ID。 I already have a method that exists that goes and gets the currently existing program Id's in the database.
我已经有一个存在的方法,该方法可以获取数据库中当前存在的程序ID。 Do I go get the program Id's and then compare the two lists before I execute the insert statement?
在执行insert语句之前,我是否要获得程序ID并比较两个列表? Can I use Linq to do the comparison?
我可以使用Linq进行比较吗? Is there a better way?
有没有更好的办法?
The method that gets the program Id's looks like this: 获取程序ID的方法如下所示:
public static List<Programs> GetPrograms(int id)
{
var sql = new StringBuilder();
sql.Append("select Id, Desc from dbo.Programs where Id = @id");
return con.Query<Programs>(sql.ToString(), new { Id = id }, commandType: CommandType.Text).ToList();
}
After doing some looking at all the options, it seems like some options for my situation are to do one of the following: 在仔细研究了所有选项之后,似乎适合我的情况的一些选项是执行以下操作之一:
Since my objective was to accomplish this task using Linq and Dapper, I have opted for the first option. 由于我的目标是使用Linq和Dapper完成此任务,因此我选择了第一个选项。 Here is the linq statement I made to get only the values I needed:
这是我仅获取所需值的linq语句:
save.ProgramList = hiddenFieldProgramIds.Value.Split(',')
.Select(n => new Programs(){ id = int.Parse(n) })
.Where(n => !program.ProgramList.Select(d => d.id).Contains(n.id)).ToList();
Then the dapper call is just a straight forward insert statement using a var based on the previous advice. 然后,dapper调用只是基于先前建议的使用var的直接插入语句。
var sql = @"insert into dbo.programTable(Id) select @id";
con.Execute(sql, new { id = id }, commandType: commandType.Text, commandTimeout: 5000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.