I have noticed that for some reason my objects that are neither coming from a query nor are added with ObjectContext.MySet.AddObject(myObj) are somehow attached to the ObjectContext.
foreach (SomeClass someObject in someSet)
{
//it says an object is added...
MessageBox.Show(someObject.EntityState.ToString());
foreach (SomeProperty someProperty in someObject.SomeProperty)
{
//type is given above
someObject.someProperty = type;
}
var existing = from o in db.SomeObjectSet
where o.Name == someObject.Name
select o;
if (existing.Count() == 0)
{
db.SomeObjectSet.AddObject(someObject);
}
//apparently I have to detach them because
//they are already attached for some reason
else
{
db.Detach(vulnerability);
}
}
db.SaveChanges();
Please, note that someSet doesn’t come from a database it comes from a different type of source, say a text file.
Normally, I’d never need to detach an object because it’s not attached, but not in this case apparently.
If you associate an object with another object that has already been added to the context, it will also be pending for insertion next time GetChanges is called (which is part of SubmitChanges). This is based on my experience with LINQ to SQL; I assume entity framework is similar.