phnx47 / dapper-repositories

CRUD for Dapper

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

InsertAsync throws an exception

CnytSntrk opened this issue · comments

commented

Hi,

I'm getting an exception while trying to insert and record. It's inserts records into DB but also throws an exception as "Null object cannot be converted to a value type".

Exception Detail:

Error parsing column 0 (Id=)

I'm using MSSql .net core 3.1. The table has the only Name and Id fields Id is guid and creates by DB. (newid())

Dapper v.2.0.78
MicroOrm.Dapper.Repositories v.1.15.0
`
[Table("Test")]
public class Test : BaseKeyEntity
{
[Column(nameof(Name))]
public string Name { get; set; }
}

public class BaseKeyEntity
{
[Key, Identity]
[Column(nameof(Id))]
public virtual Tkey Id { get; set; }
}
Service method:

public async Task CreateAsync(TestDto test)
{
var testEnt = new Test() { Name = test.Name };
await _dbContext.TestRepository.InsertAsync(testEnt);
return testEnt;
}

Repo class:

public class TestRepository : RepositoryBase, ITestRepository
{
public TestRepository(IDbConnection connection) : base(connection)
{
}
}
`

I do not think get a GUID from the database is possible. SCOPE_IDENTITY or @@IDENTITY can give you the last identity(int) used based on the counter but as GUID is completely random, it may not be possible.

Not sure if you've an option to redesign your dB but I would either make my client app create a new GUID and save to the dB or have another unique key in the table and return that instead.

commented

@harshitgindra Adding a SELECT SCOPE_IDENTITY(); in the insert query works like a charm. Returns a inserted record GUID.

@CnytSntrk
Can you share a sample? I tried few things but I wasn't able to get the GUID back.

Here's what I tried
Table structure

CREATE TABLE dbo.TestGuid
(
    TestGuidId UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWSEQUENTIALID(),
	Name NVARCHAR(100) NOT NULL,
	CreatedOn DATETIME2 DEFAULT (GETDATE())
);

Insert script

INSERT INTO dbo.TestGuid( Name)
VALUES( 't')
SELECT SCOPE_IDENTITY();

When I run the insert script, I do not get back the GUID.

If suggest if there's anything I can do to my table structure or insert script to get the guid back.

Thanks in advance.

commented

@harshitgindra Hi sorry i forgot tell you. I also added OUTPUT inserted.Id before VALUES word

Query should be like

INSERT INTO dbo.TestGuid( Name)
OUTPUT inserted.Id
VALUES( 't')
SELECT SCOPE_IDENTITY();

I can share my GenericRepo if needed

Ahh ! Got it...
That makes sense.. By adding output, it worked for me as well.
Thanks for the clarification and sharing the example.

commented

@harshitgindra your welcome sir

@harshitgindra @CnytSntrk Is this still problem? Can we close it?