Search code examples
primary-keyaspnetboilerplateunique-constraint

Cannot delete record from table which has Identity column


I have a table which has the code as primary key instead of Id, When I call DeleteAsync method I get the exception Message = "Cannot update identity column 'Id'.".

[Table("Test")]

public class Test: FullAuditedEntity<int>

{

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
new public int Id { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual int Code { get; set; }

public async Task DeleteTest(int code)
    {


        try
        {
            await _supplierRepository.DeleteAsync(p => p.Code== code);
        }
        catch (Exception ex)
        {

        }
    }

But If I remove Id column from the table, it works fine. I want both Id column and Code column as PK.


Solution

  • It is recommended that We should use Id as PK and make other columns as a unique constraint. So if you use Id as PK, you won't face such issues.