InsertOrUpdate throwing error for identity primary column

c# entity-framework-core linq linq2db sql-server

Question

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.'
1
0
9/7/2019 1:31:41 PM

Accepted Answer

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
        });
}
1
9/9/2019 5:26:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow