Unit testing with Effort - Adding records with identity off

effort mstest objectcontext unit-testing

Question

I am using using Effort (for EF4) to do some unit tests.

var ctx= Effort.ObjectContextFactory.CreateTransient<TheContext>(Shared.Connection);
ctx.companies.AddObject(new company() { ID = 100, name = "Agent", is_agent = true });
ctx.SaveChanges(System.Data.Objects.SaveOptions.DetectChangesBeforeSave);

The ID column in the company is an identity field. After executing the above query, it turns out the ID value is 1 instead of 100. Is there any way to control Identity_insert while using Effort

Accepted Answer

This is just to add the solution on this thread. @MrBlueSky add the archieved links of the solution on the comments above. But, DbConfiguration which is used on the link, does not exists anymore on the latest Effort. The solution still exists on Effort.EF6 [version="1.3.0"]. And you can use the method SetIdentityFields on EffortConnection.DbManager to turn on or off the identity fields

if (Effort.DbConnectionFactory.CreateTransient() is EffortConnection connection)
{
    connection.Open();
    connection.DbManager.SetIdentityFields(false);
    connection.DbManager.ClearMigrationHistory();
    connection.Close();
}

Turning on

// Add data with explicitly set id
Person initPerson = new Person { Id = 5, FirstName = "John", LastName = "Doe" };
dataInitContext.People.Add(initPerson);
dataInitContext.SaveChanges();

Assert.AreEqual(5, initPerson.Id);

// Enable identity field
connection.Open();
connection.DbManager.SetIdentityFields(true);
connection.Close();



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why