Can SaveChanges() in EF cause unadded objects to be inserted?
I have some code that is a result of pretty much my first effort to do TDD for an actual work project. Attempting to bootstrap, I created an entity model and tests that assert the presence of data records required materialize a report, the first concrete goal I have identitfied.
I thought it was working reasonably well until I found code that looks like it has a bug, and YET test still passes.
Here are the snippetts: The bug (I think) is a missing call to AddObject().
If anyone has the patience/inclination to look at the whole thing, I pasted it into a gist.
Test Code:
TestFactory target = new TestFactory(@"data source=biz2\da;initial catalog=DirectAgents;integrated security=True;");
DirectAgentsEntities actual = target.Create();
Assert.IsNotNull(actual);
var advertisers = actual.Advertisers.OrderBy(c => c.Id).ToList();
Advertiser advertiser1 = advertisers.ElementAt(0);
Assert.AreEqual("Advertiser 1", advertiser1.Name);
Implementation Code:
public TestFactory(string connectionString)
{
this._connectionString = connectionString;
}
public DirectAgentsEntities Create()
{
CleanUp(this.DirectAgentsEntities);
AddAdvertiserClients();
var db = this.DirectAgentsEntities;
return db;
}
private void AddAdvertiserClients()
{
var db = this.DirectAgentsEntities;
Advertiser a;
a = new Advertiser
{
Name = "Advertiser 1",
Client = db.Clients.First(c => c.Name == "Client 1")
};
db.SaveChanges();
}
private Direct开发者_运维知识库AgentsEntities DirectAgentsEntities
{
get
{
string entityConnectionFormat = @"metadata=res://*/Formss.AB2.Model.ABModel.csdl|res://*/Formss.AB2.Model.ABModel.ssdl|res://*/Formss.AB2.Model.ABModel.msl;provider=System.Data.SqlClient;provider connection string=""{0};multipleactiveresultsets=True;App=EntityFramework""";
string entityConnectionString = String.Format(entityConnectionFormat, _connectionString);
return new DirectAgentsEntities(entityConnectionString);
}
}
private string _connectionString;
How can the row get added without a call to AddObject? Should I look closer at my code for a subtle bug?
I believe you are saying that you feel an AddObject
is needed after creating the Advertiser
?
If I have misunderstood the question, my apologies.
When you link the Advertiser
to a Client
, what is happening in the generated code is that the Advertiser
is also being added to the Client.Advertisers
collection at the other side of the relationship.
This gets noted as a change on the Client
object and saved by the SaveChanges
call.
精彩评论