EF6 + MySQL - 在单个SaveChanges中插入2个相关对象时出错

时间:2014-03-03 04:16:12

标签: mysql entity-framework entity-framework-6

我正在使用EF6和MySql并在一次调用中插入两个新的相关对象Client和Quote(其中Quote有一个Client)以保存更改。这应该映射到客户端表的插入和引用表的插入。代码是:

        var client = new Client();
        db.Client.Add(client);            
        var quote = new Quote();
        quote.Client = client;
        db.Quote.Add(quote);

        db.SaveChanges();

例外是:

Additional information: An error occurred while updating the entries. See the inner exception for details.

   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
  at MyTestClass... 

内部异常是:

{"The specified value is not an instance of a valid constant type.\r\nParameter name: type"}

   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction, Boolean throwOnClosedConnection)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(Boolean throwOnClosedConnection)
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__33()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass28.<SaveChanges>b__25()
   at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()

实体类:

public class Client
{
    //AUTO_INCREMENT
    [Key]
    public long Id { get; set; }
    ....
}

public class Quote
{

    //AUTO_INCREMENT
    [Column("id")]
    [Key]
    public long Id { get; set; }

    [Column("client")]
    [ForeignKey("Client")]
    public long ClientId { get; set; }

    public virtual Client Client { get; set; }
    ...
}

库:

  • EF6
  • MySql.Data.dll v6.8.3
  • MySql.Data.Entity.EF6.dll v6.8.3

如果我在db.Client.Add(客户端)行之后添加db.SaveChanges(),它将正常工作,但我想尽可能晚地进行SavChanges以对数据库调用进行分组。什么可能出错的想法?​​

3 个答案:

答案 0 :(得分:1)

我无法重现这一点,我的测试用例的更多详细信息可以在http://forums.mysql.com/read.php?38,608603,608603#msg-608603(您也发布了问题的地方)中找到。

感谢。

答案 1 :(得分:0)

只需在客户端类中定义一组引号,例如

public IList<Quotes> quotes {get;set;}

并添加

等记录
var client = new Client();
var quote = new Quote();
client.Quotes.Add(quote);
db.client.Add(client);
db.SaveChanges();

并尝试

答案 2 :(得分:0)

问题是由于here所描述的签名/未签名的bigints造成的。