选项1
session.Clear(); // to get rid associations of the objects in memory
session.CreateQuery("delete from MyClass").ExecuteUpdate();
foreach(var entity in CreateNew())
session.Save(entity);
选项2
session.CreateQuery("delete from MyClass where Id not in (:ids)")
.SetParameterList("ids", newIds)
.ExecuteUpdate();
foreach (var id in newIds)
{
var entity = session.Get<MyClass>(id); // returns the cached instance if present or the database instance or null if non existant
if (entity == null)
{
entity = new MyClass { Id = id };
session.Save(entity);
}
Populate(entity);
}
选项3
var newEntities = CreateNew();
session.CreateQuery("delete from MyClass where Id not in (:ids)")
.SetParameterList("ids", newEntities.Select(x => x.Id).ToArray())
.ExecuteUpdate();
foreach(var entity in newEntities)
session.Merge(entity); // will get the object with the same id and copies over properties over
你能不能不要在此处使用NHibernate的? –
我正在使用NHibernate。我现在已经实施了第二个选项,它给了我需要的确切行为,尽管需要更多的努力。 –
使用createsql和truncate删除行。然后插入。那样有用吗? – Rippo