[英]EF6 with MySQL - can't add new row
編輯:問題是因為我愚蠢地從表中摘下了主鍵,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
謝謝你的幫助!
聽起來插入的問題是您沒有在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使用不正確的SELECT
語句位置發出INSERT INTO
查詢,這導致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>
相關問題:
<?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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.