RepoDB: [Bug] Enumeration: Property Int - Is not working

Hi

I’m using RepoDb.SqlServer version 1.1.1 and have the following problem/bug with enums. I want to save the enum as int in the database and according to the documentation this should work.

Setup

Database

CREATE TABLE dbo.Customer
(
  [Id] int NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED
  , [CustomerTypeId] int NOT NULL FOREIGN KEY REFERENCES dbo.CustomerType(Id)
  , [CustomerNumber] varchar(50) NULL
  , INDEX IX_Customer_CustomerNumber UNIQUE (CustomerNumber)
);

Model

public class Customer
{
	public int Id { get; init; }
	public CustomerType CustomerTypeId { get; set; }
	public string CustomerNumber { get; init; }
}

public enum CustomerType
{
	Private = 1,
	Organization = 2
}

Insert call

return await connection.ExecuteScalarAsync<int>(@"
	DECLARE @LastId TABLE (id int);

	INSERT INTO dbo.Customer
	OUTPUT INSERTED.[Id] INTO @LastId
	VALUES(@CustomerTypeId, @CustomerNumber);

	SELECT id FROM @LastId
", customer);

This gives me the following error:

Microsoft.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'Private' to data type int.

If I use the [TypeMap(DbType.Int32)] attribute it works.

If i use RepoDb.TypeMapper.Add<CustomerType>(DbType.Int32); just after call to RepoDb.SqlServerBootstrap.Initialize(); it gives me the same error so only the attribute seems to work.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 18 (18 by maintainers)

Most upvoted comments

@mikependon Yeah that is how I usually do it: int in the database with a table for it to be able to have foreign key constraints. I have not problem with RepoDb using NVARCHAR/TEXT as default but it would be nice to not have to map all enums manually but just set a flag or something when doing the initialization part. Something like:

RepoDb.TypeMapper.DefaultEnumConversion = EnumConversion.Int;
RepoDb.TypeMapper.DefaultEnumConversion = EnumConversion.Nvarchar;

Using an enum and not bool since more options might be nice and I think it is clearer in this instance too.

Okay good to know 😃 I totally understand your conundrum and have no problem with the suggested solutions.

One question though, why does not this work: RepoDb.TypeMapper.Add<CustomerType>(DbType.Int32); I tought this would cast it to int for every use case? I can use your suggestion ofc just curious why this does not work.

Oh and maybe add some kind of info about it in the documentation so what you described to me here is clear there as well.

Thanks for the clarrification. The multiple insertion is not supported in RepoDB, so what you did is correct if you use the raw SQL execution.

Anyway, this issue will be a part of the next beta release and that is very soon.