【发布时间】:2015-10-07 11:05:00
【问题描述】:
我有一个系统,它使用实体框架来对抗运行良好的 SQL Server 数据库。最近我决定迁移到 MySql 作为后端。该错误是由一些对 SQLServer 运行良好但对 MySql 失败的代码引起的。
MySql 5.6.27,EF6。
我有一个包含 1 列(称为 Id)的表,我想将其用作序列计数器。我通过将 Id 设为主键并自动生成来实现这一点。
这是表格定义:
create table tblCompanySequence (
Id int auto_increment primary key not null default 1
);
这里是对应的c# def:
using System.Data.Linq.Mapping;
namespace Foo.DataAccess.EF.Entity
{
[Table(Name = "tblCompanySequence")]
public class EFCompanySequence
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int Id { get; set; }
}
}
这里是代码:
var newSeq = new EFCompanySequence();
var tableSeq = context.GetTable<EFCompanySequence>();
tableSeq.InsertOnSubmit(newSeq);
context.SubmitChanges();
var newId = newSeq.Id;
我在调用提交更改时遇到错误。
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in System.Data.Linq.dll
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT VALUES
SELECT CONVERT(Int,SCOPE_IDENTITY()) AS `value`' at line 1
我尝试了多种排列方式,例如:
create table tblCompanySequence (
Id int auto_increment not null,
primary key (Id)
);
并在 EF 表对象上使用 DbGenerated 注释,但仍然碰壁。
非常感谢任何建议。
干杯, 安迪
更新 1:
这是我的配置设置(按照https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html设置)
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
更新 2:
我在另一个网站上读到,我可以使用以下代码来克服这个问题。
var newId = context.ExecuteCommand("insert into tblCompanySequence values (null); select LAST_INSERT_ID();");
这段代码成功地在数据库中插入了一个增加了id的新行,但是select的返回值总是1。
我确定这一定是我做错了。
【问题讨论】:
-
scope_idntity() 是一个 tsql 函数,而不是一个 mysql 函数。您是否将 EF 配置为使用 mysql 而不是 ms sql?
-
在 MySql 方面,我是一个相对的菜鸟。我在连接字符串上设置了 Sql Server Mode 开关。你是这个意思吗。
标签: c# mysql entity-framework auto-increment mysql-connector