我有一个系统使用实体框架对运行良好的SQL Server数据库。最近我决定将MySql作为后端。该错误是由一些对SQLServer运行良好的代码造成的,但是对MySql失败。MySql实体框架auto_increment错误
MySql 5.6.27,EF6。
我有一个表有1列(称为Id),我想用作序列计数器。我通过将Id作为主键和auto_generated来实现这一点。
下面是表DEF:
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
我已经尝试了数排列,e.g:
create table tblCompanySequence (
Id int auto_increment not null,
primary key (Id)
);
,并使用EF表对象DbGenerated注解,但仍创下了同一面墙上。
任何建议非常感谢。
干杯, 安迪
UPDATE 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到数据库中,但是从选择的返回值始终为1
我敢肯定,这一定有什么明显我做错误。
scope_idntity()是一个tsql函数,而不是一个mysql函数。你配置EF使用MySQL而不是MS SQL? – Shadow
谈到MySql时,我是一个相对的noob。我在连接字符串上设置了Sql Server Mode开关。你是这个意思吗。 –
andy