Reputation: 4701
I have 2 databases - one for live, the other for production
I need to replicate an issue on live, and so I thought the best thing is to copy the tables from my live database to my local database!
This means copying several tables (relational in my SQLExpress database) to my local SQL Server Compact db.
I am unable to do this because I get the following exception
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
My effort is
var dc = new DalCf.StagePlanEntities(Bll.ProgramState.LIVE-ConnectionString); //query LIVE
var account = dc.Accounts.Single(a => a.EmailAddress.Contains(emailaddress));
dc = null; //does not remove the tracking
var localDc = new DalCf.StagePlanEntities(Bll.ProgramState.LOCAL-ConnectionString);//now LOCAL
localDc.Accounts.Add(account);
localDc.SaveChanges();
Is this even the best way to duplicate the tables?
Upvotes: 0
Views: 49
Reputation: 223
The dc.Accounts.Single() produces a tracked entity. You can add ".AsNoTracking()" to the query to disable this feature (for that particular query).
var account = dc.Accounts.AsNoTracking().Single(a => a.EmailAddress.Contains(emailaddress));
https://learn.microsoft.com/en-us/ef/core/querying/tracking
By default, queries that return entity types are tracking. Which means you can make changes to those entity instances and have those changes persisted by SaveChanges(). In the following example, the change to the blogs rating will be detected and persisted to the database during SaveChanges().
Upvotes: 1