Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InsertOrUpdate throwing error for identity primary column

I was following article for InsertOrUpdate using Entity Framework Core and SQL Server.

http://blog.linq2db.com/2015/05/linq-crud-operations.html

So my linq2db query is same as their documentation.

using (var db = new DataConnection())
{
    db.GetTable<TestTable3>()
        .InsertOrUpdate(
            () => new TestTable3
            {
                ID   = 5,
                Name = "Crazy Frog",
            },
            t => new TestTable3
            {
                Name = "Crazy Frog IV",
            });
}

But in my case Id is auto incremented identity primary column. So I am getting error as below.

System.Data.SqlClient.SqlException: 'Cannot insert explicit value for identity column in table 'TestTable3' when IDENTITY_INSERT is set to OFF.'

Now I know that identity column cannot be provided. But if I don't provide then it is throwing error as

LinqToDB.Linq.LinqException: 'InsertOrUpdate method requires the 'TestTable3.Id' field to be included in the insert setter.'
like image 450
Anonymous Creator Avatar asked Mar 01 '26 12:03

Anonymous Creator


1 Answers

If you do not need retrieving just inserted value, there is overload of InsertOrUpdate function which has additional parameter for duplicate key:

using (var db = new DataConnection())
{
    db.GetTable<TestTable3>().InsertOrUpdate(
        () => new TestTable3
        {
            Name = "Crazy Frog"
        },
        e => new TestTable3
        {
            Name = "Crazy Frog"
        },
        () => new TestTable3
        {
            ID = 5
        });
}
like image 56
Svyatoslav Danyliv Avatar answered Mar 04 '26 03:03

Svyatoslav Danyliv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!