【问题标题】:Dapper.Contrib + MS Access: Error - Characters found after the end of the SQL statementDapper.Contrib + MS Access:错误 - 在 SQL 语句结束后找到的字符
【发布时间】:2018-06-24 13:13:44
【问题描述】:

我将 Dapper ORM 与 Contrib 包一起使用。 SELECT 查询完美运行,但我的问题是当我尝试 INSERT 数据时。

Visual Studio 2017 返回此消息:

在 SQL 语句结束后找到的字符

使用 Dapper(没有 Dapper.Contrib)执行的基本查询工作正常。但我需要数据库中最后插入的 id。

在 MS Access 2007 数据库中插入数据的函数代码:

public string AddCustomer(string lastName, string firstName)
{
    using (var connection = new OleDbConnection(connectionString))
    {
        try
        {
            connection.Open();

            // Inserts data into the database.
            var insertion = connection.Insert(
                new Customer { Customer_lastName = LastNameManipulation(lastName), Customer_firstName = FirstNameManipulation(firstName) }
            );

            // Defines new customer.
            Customer customer = new Customer
            {
                Customer_id = Convert.ToInt32(insertion),
                Customer_lastName = LastNameManipulation(lastName),
                Customer_firstName = FirstNameManipulation(firstName)
            };

            // Insertion into data List.
            data.AddCustomer(customer);

            message = "Customer added with success.";
        }
        catch (Exception e)
        {
            message = e.Message.ToString();
        }
        finally
        {
            connection.Close();
        }

        return message;
    }
}

客户类:

using System;
using Dapper.Contrib.Extensions;

namespace DataLibrary
{
    [Serializable]
    [Table("Customer")]
    public class Customer
    {
        [Key]
        [Computed]
        public int Customer_id { get; set; }

        [Write(true)]
        public string Customer_lastName { get; set; }

        [Write(true)]
        public string Customer_firstName { get; set; }
    }
}

【问题讨论】:

    标签: c# ms-access dapper dapper-contrib


    【解决方案1】:

    您正在使用 Dapper.Contrib,并且您的数据库是 MS Access。您的 INSERT 调用正在生成两个 SQL 查询。首先,如您所料,插入记录。二是在屏幕后面获取新生成的id。

    所以,生成的查询看起来像这样:

    INSERT INTO Table (......) VALUES (....);
    SELECT @@IDENTITY";
    

    这两个查询都在单次往返中执行。 MS Access 不支持此功能。 MS Access 不理解分号后的字符,即SELECT @@IDENTITY";

    请参考this链接。

    Jet 数据库引擎不支持批量执行多个语句或使用输出参数,因此无法使用这些技术中的任何一种来返回分配给插入行的新Autonumber 值。

    解决方案是分别执行这两个查询或不执行第二个查询;以不同的方式处理它。但是,您正在使用 Contrib,它会为您生成查询。因此,您可以在这里做的事情非常少(自己修改 Contrib 代码)。

    坦率地说,我不知道解决方案。我从未使用过 Dapper.Contrib。可能这是在较新版本中修复的。或者可能是 Contrib 不支持 MS Access。我只是试图向你解释这个问题。请参考其他answer,它讨论了相同的问题,但使用了 Dapper Extensions。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多