0

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Saadi
  • 2,211
  • 4
  • 21
  • 50

1 Answers1

0

From How do I detach objects in Entity Framework Code First?

var orders = _t1Db.Orders
    .AsNoTracking() // Query without tracking
    .Where(o =>
                interfaceOrders.All(x => x.id != o.id)
    )
    .ToList();
Community
  • 1
  • 1
robaudas
  • 1,538
  • 1
  • 9
  • 12