原始SQL命令不使用Entity Framework执行

时间:2014-10-27 06:17:02

标签: c# sql entity-framework rawsql

我无法使用以下原始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语句时,一切都按预期工作,但是当我使用实体框架时,表格不会被填充,也不会生成异常。

1 个答案:

答案 0 :(得分: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();

显然,这个statemnent会提交我的数据库更改,因此TempAreaTypeTempConstructionType表在执行第三个命令时没有任何数据。当我在Microsoft SQL Server Management Studio中执行commadn时,我的更改已经提交到数据库并且命令有效。

解决方法是调用

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();