Dapper扩展将数据插入SQL Server

zpgglvta  于 2023-01-29  发布在  SQL Server
关注(0)|答案(1)|浏览(220)

数据库表:

CREATE TABLE [dbo].[EmployeeDetails]
(
    [id] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
    [Name] [varchar](max) NULL,
    [Emailid] [varchar](max) NULL,
    [department] [varchar](max) NULL,
    [Salary] [int] NULL,
    [Profile] [varchar](max) NULL,
    [Description] [varchar](max) NULL,
    [ReferencesId] [int] NULL
)

型号分类:

public class Employee
{
    #region properties
    public int Id { get; set; }
    public string? Name { get; set; }
    public string? Emailid { get; set; }
    public string? department { get; set; }

    public int salary { get; set; }

    public string? Profile { get; set; }
    public string? Description { get; set; }
    #endregion
}

类Map器

public class EmployeeMapper : ClassMapper<Employee>
{
    public EmployeeMapper() 
    {
        Table("EmployeeDetails");

        Map(x => x.Id).Key(KeyType.Identity).Column("Id").Type(System.Data.DbType.Int32);           
        Map(x => x.Name).Column("Name");
        Map(x => x.Emailid).Column("Emailid");
        Map(x => x.department).Column("department");
        Map(x => x.salary).Column("Salary");
        Map(x => x.Profile).Column("Profile");
        Map(x => x.Description).Column("Description");
    }
}

插入代码:

public int Add(T entity)
{
    int count = 0;

    using (var con = _dapperContext.CreateConnection())
    {
        int id = con.Insert(entity);

        if (id > 0)
        {
            count++;
        }
    }

    return count;
}

我得到这个错误:

System.ArgumentException:类型为"System.Int64"的对象无法转换为类型"System.Int32"。
我在页面上显示了这个异常,但是数据被成功插入到数据库中。我的数据库数据类型和模型类数据类型都是相同的,但是我仍然在页面上看到这个"转换错误
我需要使用ASP.NET Core Razor页面中的Dapper扩展向数据库表中插入一个新行
enter image description here

ekqde3dh

ekqde3dh1#

我在页面上显示了这个异常,但是数据被成功插入到数据库中。我的数据库数据类型和模型类数据类型都是相同的,但是我仍然在页面上看到这个"转换错误
好吧,一开始我认为你在做一些愚蠢的事情。出于我的好奇心,我进入它,并了解到问题不在您的代码中,它的Dapper-Extensions问题。我已经调查了相当长的一段时间与他们的文档,似乎是它的旧版本,目前他们不支持它。I have gone through this official document.

    • 复制的问题:**

我已经重现了从Dapper-Extensions方法抛出的问题,如下所示:
Dapper延伸方法:

例外情况:

堆栈跟踪:

at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
   at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
   at DapperExtensions.DapperImplementor.InternalInsert[T](IDbConnection connection, T entity, IDbTransaction transaction, Nullable`1 commandTimeout, IClassMapper classMap, IList`1 nonIdentityKeyProperties, IMemberMap identityColumn, IMemberMap triggerIdentityColumn, IList`1 sequenceIdentityColumn)
   at DapperExtensions.DapperImplementor.Insert[T](IDbConnection connection, T entity, IDbTransaction transaction, Nullable`1 commandTimeout)
   at MVCApps.Controllers.UserLogController.Add() in D:\MyComputer\MsPartnerSupport\MVCApps\Controllers\UserLogController.cs:line 1371
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
    • 注:**

在调试和重现问题时,我尝试在两端使用数据类型int以及其他数据类型,例如bigint,但仍然发生转换错误,我发现这个问题在Dapper-Extensions方面是已知的。因此,一个数据类型相应地工作,即GUID。我仍然不确定,这些Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast是如何干预这里的。

    • 解决方案-变通办法:**

到目前为止,intbigint总是抛出'Object of type 'System.Int64' cannot be converted to type 'System.Int32'.',因此,尚不清楚原因是什么来自DapperExtensions.DapperExtensions.Insert()方法。
此外,为了避免上述错误,我们可以采取以下措施:
POCO型号:

public class Employee
    {

        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Emailid { get; set; }
        public string Department { get; set; }
        public int Salary { get; set; }
    }
    • 注:**

除了Guid目前不工作之外,我不确定这背后的原因。所以如果你想坚持你的实现,你必须使用Guid
数据库架构:

CREATE TABLE Employee(
      [Id] UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
      [Name] [varchar](25) NULL,
      [Emailid] [varchar](100) NULL,
      [Department] [varchar](25) NULL,
      [Salary] [int] NULL,
)

Asp.Net核心控制器/存储库方法:

public int Add()
        {
            int count = 0;

            Employee employee = new Employee();
            employee.Name = "Kudiya";
            employee.Emailid = "email@someemail.com";
            employee.Department = "Dapper";
            employee.Salary = 500;
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Insert(employee);
                Guid Id = employee.Id;
               
                if (Id != null)
                {
                    count++;
                }
            }
            return count;
        }
    • 注意:**请根据您的方案和上下文更新代码段。
    • 输出:**

    • 注:**此外,基于stacktrace,如果有人有确切的解释或发现,请让我知道。我很乐意更新我的答案。

相关问题