How to check for UNIQUE in sql table using c#?

Viewed 47

I have a table with a UNIQUE constraint on a Code column.

upon inserting a new row to that table using c# how would i check if the Code already exists?

Here is what i do when adding a new row to the database:

tableDB = await context.Table.FirstOrDefaultAsync(c => c.TableId == table.TableId); // here the table object is what i want to insert

if(tableDB == null) {
  tableDB = new Table()
  // i have code here that i do not show because is not relevant, FYI i need this if statement
} else {
  tableDB.TableId = table.TableId,
  tableDB.Code = table.Code,
}
await context.SaveChangesAsync();

What that code does:

  • check if the given table.TableId exists in the database if the object is null then it means i want to ADD and not EDIT
  • else i can change the existing tableDB using what user provided in front-end

Now how do i check if the table.Code is already in the table ence is not UNIQUE when adding new element BUT not throwing error when editing existing record?

I think i would have to do this:

var tableName= await context.Table.FirstOrDefaultAsync(c => c.Code == table.Code);
if(tableDB != null && tableName != null) {
    if(tableName.TableId == table.TableId) {
        // the duplicate code found is corresponding to the TableId i want to edit ence i can edit
    } else {
       // throw some errors that duplciate is found
     }

}

But i am still stuck at this after an hour trying to fix it or figureit out? Can someone help me with this?

0 Answers
Related