LINQ to Sql: Insert instead of Update
- by Christina Mayers
I am stuck with this problems for a long time now.
Everything I try to do is insert a row in my DB if it's new information - if not update the existing one.
I've updated many entities in my life before - but what's wrong with this code is beyond me (probably something pretty basic)
I guess I can't see the wood for the trees...
private Models.databaseDataContext db = new Models.databaseDataContext();
internal void StoreInformations(IEnumerable<EntityType> iEnumerable)
{
foreach (EntityType item in iEnumerable)
{
EntityType type = db.EntityType.Where(t => t.Room == item.Room).FirstOrDefault();
if (type == null)
{
db.EntityType.InsertOnSubmit(item);
}
else
{
type.Date = item.Date;
type.LastUpdate = DateTime.Now();
type.End = item.End;
}
}
}
internal void Save()
{
db.SubmitChanges();
}
Edit:
just checked the ChangeSet, there are no updates only inserts.
For now I've settled with
foreach (EntityType item in iEnumerable)
{
EntityType type = db.EntityType.Where(t => t.Room == item.Room).FirstOrDefault();
if (type != null)
{
db.Exams.DeleteOnSubmit(type);
}
db.EntityType.InsertOnSubmit(item);
}
but I'd love to do updates and lose these unnecessary delete statements.