Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework map column which is not in old database

I have table in a new DB which contains column 'Note'. I have old DB with the same table with the same structure which have not column 'Note'. I changed edmx, I added (mapped) column 'Note' from new DB. But if I want to use edmx in old DB I have error: column doest not exists...

I try to put code to try catch, but without succesfull. Error is outside off try catch.

//---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

How can I resolve? Thanks

like image 352
Musketyr Avatar asked May 13 '13 09:05

Musketyr


1 Answers

That's kind of an 'hack', but you can choose to ignore the Note property once you're using the old database.

Look for the OnModelCreating method in your context class, and replace with:

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

Update:

Since you're using .edmx for mapping and there's currently no way to modify the mapping in runtime i assume my suggestion was indeed wrong.

I still don't get what are you trying to achieve by using the try/catch block, it doesn't matter whether you include the (missing) Note field in the query or not, since Entity Framework realizes the model is no longer compatible with the database, it will refuse to work with this database altogether.

But 2 points to keep in mind:

  • Since you're using IQueryable, your try/catch is indeed in the wrong place, the exception will be thrown only during Materialization (when trying to actually retrieving the data).

    You can materialize the query using the ToList method (among others):

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

    or move the try/catch block to wrap the foreach statement.

  • You can use System.Data.Entity.Database.CompatibleWithModel() method to early determine (upon context initialization for example) whether your model and database can still work together.

like image 123
haim770 Avatar answered Oct 25 '22 06:10

haim770