0

我在使用以下原始 SQL 命令和实体框架播种数据时遇到问题

databaseContext.Database.ExecuteSqlCommand
      (@"INSERT INTO    NatureOfBusinessRiskClass
            ( ProductSectionId ,
            NatureOfBusinessId ,
            RiskClassId ,
            ConstructionType ,
            AreaType ,
            SumInsuredLimit ,
            MaximumRate ,
            MinimumRate ,
            IsAggregated ,
            CreatedBy ,
            CreateDate)
      SELECT P.Id,T.NatureOdBusinessId,T.RiskClassId,ConstructionType,AreaType,0.00,
      0,0,0,1,GETDATE() FROM TempNatureBusiness T
            CROSS JOIN TempAreaType A
            CROSS JOIN TempConstructionType C
            CROSS JOIN ProductSection P");

当我在 Microsoft SQL Server Management Studion 中执行此 SQL 语句时,一切都按预期工作,但是当我使用实体框架时,表没有填充,也没有生成异常。

4

1 回答 1

0

问题是我还使用 RAW sql 命令来填充此查询所依赖的表以生成其内容,例如

databaseContext.Database.ExecuteSqlCommand("INSERT INTO TempAreType...");
databaseContext.Database.ExecuteSqlCommand("INSERT INTO TempConstructionType...");

然后我执行了我遇到问题的命令,

databaseContext.Database.ExecuteSqlCommand
  (@"INSERT INTO    NatureOfBusinessRiskClass
        ( ProductSectionId ,
        NatureOfBusinessId ,
        RiskClassId ,
        ConstructionType ,
        AreaType ,
        SumInsuredLimit ,
        MaximumRate ,
        MinimumRate ,
        IsAggregated ,
        CreatedBy ,
        CreateDate)
  SELECT P.Id,T.NatureOdBusinessId,T.RiskClassId,ConstructionType,AreaType,0.00,
  0,0,0,1,GETDATE() FROM TempNatureBusiness T
        CROSS JOIN TempAreaType A
        CROSS JOIN TempConstructionType C
        CROSS JOIN ProductSection P");

最后我执行了

databaseContext.SaveChanges();

显然这个语句将提交我的数据库更改,所以TempAreaTypeTempConstructionType表没有任何数据。当我在 Microsoft SQL Server Management Studio 中执行命令时,我的更改已经提交到数据库并且命令有效。

解决方案是调用

databaseContext.SaveChanges();

在第一个命令之后,然后在最后,例如

databaseContext.Database.ExecuteSqlCommand("INSERT INTO TempAreType...");
databaseContext.Database.ExecuteSqlCommand("INSERT INTO TempConstructionType...");

databaseContext.SaveChanges();

databaseContext.Database.ExecuteSqlCommand
  (@"INSERT INTO    NatureOfBusinessRiskClass
        ( ProductSectionId ,
        NatureOfBusinessId ,
        RiskClassId ,
        ConstructionType ,
        AreaType ,
        SumInsuredLimit ,
        MaximumRate ,
        MinimumRate ,
        IsAggregated ,
        CreatedBy ,
        CreateDate)
  SELECT P.Id,T.NatureOdBusinessId,T.RiskClassId,ConstructionType,AreaType,0.00,
  0,0,0,1,GETDATE() FROM TempNatureBusiness T
        CROSS JOIN TempAreaType A
        CROSS JOIN TempConstructionType C
        CROSS JOIN ProductSection P");

databaseContext.SaveChanges();
于 2014-10-27T06:45:05.920 回答