簡體   English   中英

不在舊數據庫中的實體框架映射列

[英]Entity framework map column which is not in old database

我在新數據庫中有表,其中包含“注釋”列。 我有舊DB與相同的表,具有相同的結構,沒有列'注意'。 我更改了edmx,我從新數據庫添加(映射)列'Note'。 但如果我想在舊DB中使用edmx我有錯誤:列doest不存在...

我嘗試將代碼放入嘗試catch,但沒有成功。 錯誤是在try try之外。

//---new version DB
                try
                {
                    vehicles = entities.Vehicle.Where(v => v.NumPlate == numPlate || v.Note == numPlate);
                }
                catch (Exception)
                {
                    vehicles = entities.Vehicle.Where(v => v.NumPlate == numPlate);
                }
                //---old version DB

                foreach (Vehicle vehicle in vehicles) //<------- ERROR

我怎么解決? 謝謝

這是一種'hack',但是一旦你使用舊數據庫,你可以選擇ignore Note屬性。

context類中查找OnModelCreating方法,並替換為:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        if (this.Database.Connection.Database == "Name_Of_Old_Database")
            modelBuilder.Entity<Vehicle>().Ignore(x => x.Note);
    }

更新:

由於您使用.edmx進行映射,並且目前無法在運行時修改映射,因此我認為我的建議確實是錯誤的。

我仍然沒有得到你想要通過使用try/catch塊實現的目標,是否在查詢中包含(缺少) Note字段並不重要,因為Entity Framework意識到模型不再兼容使用數據庫,它將完全拒絕使用此數據庫。

但要牢記2點:

  • 由於您使用IQueryable ,您try/catch確實是放錯了地方,異常將只在拋出Materialization (試圖真實的檢索數據時)。

    您可以使用ToList方法(以及其他方法)實現查詢:

    entities.Vehicle.Where(v => v.NumPlate == numPlate || v.Note == numPlate).ToList() ;

    或者移動try/catch塊以包裝foreach語句。

  • 您可以使用System.Data.Entity.Database.CompatibleWithModel()方法來早期確定(例如,在上下文初始化時)您的模型和數據庫是否仍然可以一起工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM