【问题标题】:how to make dbContext ExecuteSqlCommand work with new uncommitted entities如何使 dbContext ExecuteSqlCommand 与新的未提交实体一起使用
【发布时间】:2014-11-05 12:47:47
【问题描述】:

有没有办法让 ExecuteSqlCommand 与新的未提交实体一起工作。

        using (var context = new EarthContext())
        {
            var country = new Country(){
                Id = "ZZZ",
                IsoCodeAlpha2 = "ZZ",
                IsoCodeNumberic = 999
            };

            context.Countries.Add(country);

            context.Database.ExecuteSqlCommand(
            @"
              INSERT INTO dbo.Location([Line1],[CountryId])
              VALUES ('random line','ZZZ')
            ");

            context.SaveChanges();
        }

它给出了“与 FOREIGN KEY 约束冲突的 INSERT 语句”异常,因为 ExecuteSqlCommand 在新实体提交之前执行。

*代码必须在一个事务中运行,即我不能在 ExecuteSqlCommand 之前提交更改

【问题讨论】:

    标签: ef-code-first dbcontext


    【解决方案1】:

    据我所知,所有使用 context.Database.ExecuteSqlCommand 调用的 sql 查询都是在与“通用”上下文操作不同的事务上执行的。另一点是立即调用 ExecuteSqlCommand 并且像context.Countries.Add(country); 这样的所有操作(所有插入、更新或删除)都使用context.SaveChanges(); 执行。

    你应该试试:

    using (var context = new EarthContext())
    {
        var country = new Country(){
            Id = "ZZZ",
            IsoCodeAlpha2 = "ZZ",
            IsoCodeNumberic = 999
        };
    
        context.Countries.Add(country);
        context.SaveChanges(); // to commit country insertion
    
        context.Database.ExecuteSqlCommand(
        @"
          INSERT INTO dbo.Location([Line1],[CountryId])
          VALUES ('random line','ZZZ')
        ");
    }
    

    但如果你必须满足这些要求

    代码必须在一个事务中运行,即我不能在 ExecuteSqlCommand 之前提交更改

    您应该避免混合 SQL 语句和类似 EF 的代码。

    在那种情况下(我假设你已经正确定义了所有 FK)你应该能够这样做:

    using (var context = new EarthContext())
    {
        var country = new Country(){
            Id = "ZZZ",
            IsoCodeAlpha2 = "ZZ",
            IsoCodeNumberic = 999
        };
    
        context.Countries.Add(country);
        country.Locations.Add(new Location() { Line1 = "random line" } );
    
        context.SaveChanges();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多