I'm trying to get data from dbContext and save it to other dbContext. Actually, I want to import some data base on some validation from database A and store it to database B. I know there are other ways to do that but I want to it using EF with two DBContexts.
Here is the scenario:
I've to DbContext class with names: T1Entities
, InterfaceDbContext
these dbContext are using the same Models.
Like I've a class with name orders
and I'm using the same class for other of these context.
Like this way:
public partial class T1Entities : DbContext
{
public virtual DbSet<Order> Orders { get; set; }
}
public class InterfaceDbContext : DbContext
{
public DbSet<Order> Orders { get; set; }
}
and in my GetOrder
function, I'm trying to get only those orders that are not present in InterfaceDbContext and trying to insert on that context.
public List<orders_mstr> GetOrders()
{
// getting interface db Orders
var interfaceOrders = _interfaceDb.Orders.ToList();
// getting T1 db orders which are not present in it interface db
var orders = _t1Db.Orders
.Where(o =>
interfaceOrders.All(x => x.id != o.id)
)
.ToList();
// trying to save the first object.
_interfaceDb.Orders.Add(orders[0]);
_interfaceDb.SaveChanges();
}
I'm having exception here while saving:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Please note: I've to use the save Order class for other of the contexts. I know we can do that by creating different other class for each of these contexts.