Cannot delete record from table which has Identity column

↘锁芯ラ 提交于 2019-12-12 04:04:11

问题


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.


回答1:


What is happening is, by FullAuditedEntity<int> automatically creates an Id field of integer. You don't need to do this:

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

If you want to create a table with a composite key, go ahead and just add your Code Field without replicating the Id field. Then you will have no problems.




回答2:


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.



来源:https://stackoverflow.com/questions/46173881/cannot-delete-record-from-table-which-has-identity-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!