2
    public class Customer
    {
        [ExplicitKey]
        public int Id { get; set; }

        [Write(false)]
        public string FullName { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string EmailToRevalidate { get; set; }
        public string SystemName { get; set; }
        public int BillingAddress_Id { get; set; }
..................
..................
        public int Add(Customer customer)
        {
            using (IDbConnection conn = Connection)
            {
                var result = conn.InsertAsync(customer).Result; // need to fix this it is return 0 because of the explicitkey attribue on ID.
                return result;
            }
        }

I want Add() method to return the Id that was actually inpute ie which is in customer object. Or else I would like to return the whole object. But I need to know if the insert was successfull or not.

Is there a way to check if InsertAsync() Success = true ??

4u2c
  • 88
  • 1
  • 11
  • Just in case you decide to fall back to Dapper (bypass Contrib), [this](https://stackoverflow.com/q/37391883/5779732) may be helpful. It is in context of MS Access, but basic principle is still the same. – Amit Joshi Mar 18 '21 at 09:52

1 Answers1

0

This is because you use ExplicitKey. From the Github page:

  • [ExplicitKey] - this property represents an explicit identity/key which is not automatically generated by the database.

Dapper.Contrib is using SCOPE_IDENTITY to get the id, so the column needs to be an IDENTITY column. A "normal" INSERT doesn't return anything, so there no way to get the Id back. You could do different tricks to your SQL depending on the SQL dialect, but if you need to change the query, it wouldn't be Dapper.Contrib.

If you used Key and IDENTITY column it should work out of the box.

EDIT: If you want to check the success, just check for exceptions. There will be an exception thrown if the INSERT doesn't succeed.

Palle Due
  • 5,929
  • 4
  • 17
  • 32
  • I need to use [ExplicitKey] because I am passing my own Identity. If I use [Key] it throws and error "cannot insert value NULL for Id" – 4u2c Mar 18 '21 at 08:30
  • Sorry, I didn't explain that clearly. I was trying to convey, that what you want isn't possible. An insert isn't returning anything. If you use IDENTITY Dapper.Contrib will select SCOPE_IDENTITY for you, but that's a corner case. And anyway you have the ID, since you passed it yourself. – Palle Due Mar 18 '21 at 09:45
  • Yes correct I already have the ID. Primarily I just wanted the method to return something other than 0 to actually acknowledge that it has been successful. For now I will just have to return a bool value setting result outside using scope and using a tryCach to return result successful or not – 4u2c Mar 18 '21 at 10:21
  • How would this work with an Guid id type? Since dapper only returns a long value? – Wolfware Sep 01 '23 at 20:04