Checking for duplicates before updating with dapper linq c#

c# dapper linq


I'm relatively new to Linq and Dapper and I'm trying to find the most effecient way to make an insert happen. 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 (e.g. 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. I already have a method that exists that goes and gets the currently existing program Id's in the database. Do I go get the program Id's and then compare the two lists before I execute the insert statement? Can I use Linq to do the comparison? Is there a better way?

The method that gets the program Id's looks like this:

 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();

Popular Answer

After doing some looking at all the options, it seems like some options for my situation are to do one of the following:

  • compare the new list values to the old list values in the code behind then use a simple insert statement that passes only values that were different
  • pass the list to dao layer, go get a new copy of the list from the db, compare the lists in code then only insert the different ones
  • send the list to the db, do the comparison at the sql level using a while loop and insert

Since my objective was to accomplish this task using Linq and Dapper, I have opted for the first option. Here is the linq statement I made to get only the values I needed:

 save.ProgramList = hiddenFieldProgramIds.Value.Split(',')
     .Select(n => new Programs(){ id = int.Parse(n) })
     .Where(n => !program.ProgramList.Select(d =>;

Then the dapper call is just a straight forward insert statement using a var based on the previous advice.

 var sql = @"insert into dbo.programTable(Id) select @id";
 con.Execute(sql, new { id = id }, commandType: commandType.Text, commandTimeout: 5000);

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why