编辑:问题是因为我愚蠢地从表中摘下了主键,而EF6不适用于pks:)
我正在使用EF6和MySQL,可以使用类似...的简单内容从数据库中读取记录。
using (airtableEntities context = new airtableEntities())
{
accList = context.icqties.ToList();
}
但是,当我试图像这样向表中添加新的icqty时
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main()
{
using (airtableEntities context = new airtableEntities())
{
icqty test = new icqty()
{
ProductCode = "test",
AirTableRec = "nfklwn",
LocationCode = "AKL",
QuantityInStock = 5,
RecordRevision = 2
};
context.icqties.Add(test);
context.SaveChanges();
Console.WriteLine($"Added all new rows to db");
}
}
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ConsoleApp3
{
using System;
using System.Collections.Generic;
public partial class icqty
{
public string ProductCode { get; set; }
public Nullable<int> QuantityInStock { get; set; }
public string LocationCode { get; set; }
public int RecordRevision { get; set; }
public string AirTableRec { get; set; }
}
}
我听到一个例外
在EntityFramework.dll中发生了类型为'System.Data.Entity.Infrastructure.DbUpdateException'的未处理的异常 更新条目时发生错误。有关详细信息,请参见内部异常。发生
MySqlException:您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获取在'(SELECT
icqty
。ProductCode
,
icqty
。QuantityInStock
,
icqty
。第1行的“ LocationCod”
但是-我不明白为什么要进行选择。应该在该表中插入吗?
这里有一个屏幕截图,可帮助您了解发生了什么-https://imgur.com/a/UypWkjV
我正在使用MySql.Data.EntityFramework版本8.0.13.0
我正在运行它,因为我的appsettings.json看起来像这样
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="airtableEntities" connectionString="metadata=res://*/Accredo.csdl|res://*/Accredo.ssdl|res://*/Accredo.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;persistsecurityinfo=True;user id=root;password=*******;database=airtable"" providerName="System.Data.EntityClient" /></connectionStrings>
<entityFramework>
<defaultConnectionFactory type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.13.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.13.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
</entityFramework>
<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=8.0.13.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D" />
</DbProviderFactories>
</system.data>
</configuration>
我还向控制台添加了一些SQL日志记录,这就是我得到的
Opened connection at 3/12/2018 4:32:36 PM +13:00
Started transaction at 3/12/2018 4:32:36 PM +13:00
INSERT INTO (SELECT
`icqty`.`ProductCode`,
`icqty`.`QuantityInStock`,
`icqty`.`LocationCode`,
`icqty`.`RecordRevision`,
`icqty`.`AirTableRec`
FROM `icqty` AS `icqty`)(
`ProductCode`,
`QuantityInStock`,
`LocationCode`,
`RecordRevision`,
`AirTableRec`) VALUES (
@gp1,
5,
@gp2,
2,
@gp3)
-- @gp1: 'test' (Type = String, IsNullable = false, Size = 4)
-- @gp2: 'AKL' (Type = String, IsNullable = false, Size = 3)
-- @gp3: 'nfklwn' (Type = String, IsNullable = false, Size = 6)
-- Executing at 3/12/2018 4:32:37 PM +13:00
-- Failed in 17 ms with error: 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 '(SELECT
`icqty`.`ProductCode`,
`icqty`.`QuantityInStock`,
`icqty`.`LocationCod' at line 1
Closed connection at 3/12/2018 4:32:37 PM +13:00
Disposed transaction at 3/12/2018 4:32:37 PM +13:00
感谢您的帮助!
答案 0 :(得分:1)
听起来像是插入问题,是因为您没有在icqty
表内指定主键字段,如下表定义所示:
public partial class icqty
{
// what is the primary key field??
public string ProductCode { get; set; }
public Nullable<int> QuantityInStock { get; set; }
public string LocationCode { get; set; }
public int RecordRevision { get; set; }
public string AirTableRec { get; set; }
}
由于未在表类定义中定义主键,因此EF使用不正确的INSERT INTO
语句位置发出了SELECT
查询,这导致了DbUpdateException
,因为EF要求在表内部定义主键才能创建正确的INSERT
查询。
为缓解此问题,请在icqty
表内创建/设置主键字段:
-- add new PK column
ALTER TABLE icqty ADD COLUMN `Id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT;
-- using existing column as PK
ALTER TABLE icqty MODIFY COLUMN `existingcolumnname` INT NOT NULL PRIMARY KEY AUTO_INCREMENT;
然后通过将StoreGeneratedPattern
选项设置为Identity
或使用如下示例的属性,将其设置为自动生成的身份列:
public partial class icqty
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; } // primary key example
public string ProductCode { get; set; }
public Nullable<int> QuantityInStock { get; set; }
public string LocationCode { get; set; }
public int RecordRevision { get; set; }
public string AirTableRec { get; set; }
}
还要确保MySQL Connector .NET(MySql.Data.dll
)版本是否与相应的MySQL版本兼容并以正确的方式在web.config中注册。
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.13.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
相关问题:
Entity Framework (EF6) + MySql Database First Model Many to Many Relationship Wrong Query Generation
答案 1 :(得分:0)
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.13.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
</providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Google.Protobuf" publicKeyToken="a7d26565bac4d604" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.6.1.0" newVersion="3.6.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<connectionStrings>
<add name="DBEntities" connectionString="metadata=res://*/Model.PacsModel.csdl|res://*/Model.PacsModel.ssdl|res://*/Model.PacsModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=127.0.0.1;user id=root;password=*********;persistsecurityinfo=True;database=TestDB"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
检查mysql-connector-net和MySql.Data.dll版本,确认为8.0.13。更新.NETFramework,Version = v4.7.2