ef6 with mysql-无法添加新行

nimxete2  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(394)

编辑:问题是因为我愚蠢地从表中去掉了主键,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服务器版本对应的手册,以了解要使用的正确语法 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=&quot;server=localhost;persistsecurityinfo=True;user id=root;password=*******;database=airtable&quot;" 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

谢谢你的帮助!

bvhaajcl

bvhaajcl1#

<?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=&quot;server=127.0.0.1;user id=root;password=*********;persistsecurityinfo=True;database=TestDB&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

检查mysql connector net和mysql.data.dll版本,确认为8.0.13.update.netframework,版本=v4.7.2

lxkprmvk

lxkprmvk2#

听起来插入的问题在于没有在其中指定主键字段 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; }
}

由于表类定义中没有定义主键,因此 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>

相关问题:
实体框架(ef6)+mysql数据库第一模型多对多关系错误查询生成
dbcontext.savechanges()方法引发dbupdateexception

相关问题