2011-04-07 24 views
1

我已經繼承了一個大的C#項目,並遇到更新數據模型的問題。 我已經在wysiwyg edmx數據建模編輯器(vs2010)中進行了更新,更新看起來很好。但是,這很難說,當我運行程序,立即當它試圖訪問數據庫,我得到這個錯誤:「沒有這樣的列Extent2。」<fieldname>「問題

「SQLite的錯誤沒有這樣的列:Extent2.Country_ID」

COUNTRY_ID是一個屬性一個現有的實體(我沒有修改過),但我不知道「Extent2」是什麼。我對所有相關的項目文件進行了徹底的文本搜索,並且它沒有出現過一次。

在異常,TargetSite讀取: {System.Data.Common.DbDataReader ExecuteStoreCommands(System.Data.EntityClient.EntityCommand,的System.Data.CommandBehavior)}

不幸的是,沒有太多的更信息;沒有錯誤號碼或任何東西。 任何想法?

感謝

回答

2

Extent2是由實體框架生成的SQL表的別名。這聽起來像是在您的實體模型中有一個錯誤的關係或字段映射,導致生成的SQL命令與您的實際數據庫結構不匹配。

+0

你可能是對的,但遺憾的是,wysiwyg edmx編輯器太糟糕了,我只是最終不擔心框架內的關係,只添加了實體並手動處理了關係 – 2011-04-17 20:17:17

0

如果您的應用程序(它使用實體框架上的SQLite)在打開舊版本,有表,但沒有列可以檢測缺少的列和編程它添加數據庫,如下所示: -

private EntityFrameworkEntities _modelInstance; 

    protected override void Load() 
    { 
     bool retry = false; 
     if (!TryLoad(out retry)) 
     { 
      if (retry) 
      { 
       AddColumnToTableInDatabase(); 
       TryLoad(out retry); 
      } 
     } 
    } 

    private bool TryLoad(out bool retry) 
    { 
     bool success = false; 
     retry = false; 
     using (_modelInstance = new EntityFrameworkEntities()) 
     { 
      _modelInstance.Connection.Open(); 

      var yourQuery = from entity in _modelInstance.Entitys 
           select entity; 
      try 
      { 
       foreach (Entity entity in yourQuery) 
       { 
        var vm = new EntityViewModel(entity, this); 
        base.Children.Add(vm); 
       } 
       success = true; 
      } 
      catch (Exception ex) 
      { 
       while (ex.InnerException != null) 
        ex = ex.InnerException; 
       if (ex.Message.ToLower().Contains("no such column") && ex.Message.Split(new char[] { '.' })[1].Equals("Country_ID")) 
        retry = true; 
       log.Error(ex.Message, ex); 
      } 
     } 
     return success; 
    } 

    private bool AddColumnToTableInDatabase() 
    { 
     bool success = false; 
     StringBuilder sql = new StringBuilder(@"ALTER TABLE [Entity] ADD COLUMN [Country_ID] [text] NULL"); 
     using (_modelInstance = new EntityFrameworkEntities()) 
     { 
      _modelInstance.Connection.Open(); 
      var connection = (_modelInstance.Connection as EntityConnection).StoreConnection as SQLiteConnection; 
      using (var transaction = connection.BeginTransaction()) 
      { 
       try 
       { 
        using (var command = connection.CreateCommand()) 
        { 
         command.CommandText = sql.ToString(); 
         command.ExecuteNonQuery(); 
        } 
        transaction.Commit(); 
        success = true; 
       } 
       catch (Exception ex) 
       { 
        log.Error(ex.Message, ex); 
        transaction.Rollback(); 
       } 
      } 
     } 
     return success; 
    } 
相關問題