LINQ to SQL插入(如果不存在)
时间:2020-03-06 14:24:54 来源:igfitidea点击:
我想知道如果表中尚不存在插入记录的简便方法。我仍在尝试建立LINQ to SQL技能。
这就是我所拥有的,但似乎应该有一种更简单的方法。
public static TEntity InsertIfNotExists<TEntity>
(
DataContext db,
Table<TEntity> table,
Func<TEntity,bool> where,
TEntity record
)
where TEntity : class
{
TEntity existing = table.SingleOrDefault<TEntity>(where);
if (existing != null)
{
return existing;
}
else
{
table.InsertOnSubmit(record);
// Can't use table.Context.SubmitChanges()
// 'cause it's read-only
db.SubmitChanges();
}
return record;
}
解决方案
public static void InsertIfNotExists<TEntity>
(this Table<TEntity> table,
TEntity entity,
Expression<Func<TEntity,bool>> predicate)
where TEntity : class
{
if (!table.Any(predicate))
{
table.InsertOnSubmit(record);
table.Context.SubmitChanges();
}
}
table.InsertIfNotExists(entity, e=>e.BooleanProperty);
同意马克思的回答,但请参阅注释1.
注意1:恕我直言,在辅助方法中调用db.SubmitChanges()是不明智的,因为我们可能会中断上下文事务。这意味着,如果我们在多个实体的复杂更新过程中调用InsertIfNotExists <TEntity>,则不是一次而是分步保存更改。
注意2:InsertIfNotExists <TEntity>方法是一种非常通用的方法,适用于任何情况。如果我们只想区分从数据库中加载的实体和从代码中创建的实体,则可以使用Entity类的部分方法" OnLoaded",如下所示:
public partial class MyEntity
{
public bool IsLoaded { get; private set; }
partial void OnLoaded()
{
IsLoaded = true;
}
}
鉴于此(并注意1),InsertIfNotExists功能将简化为以下内容:
if (!record.IsLoaded)
db.InsertOnSubmit(record);
马克答案的小修改:
如果我们只关心通过主键检查实体是否存在,则可以使用Marke的答案,如下所示:
public static void InsertIfNotExists<TEntity>
(this Table<TEntity> table
, TEntity entity
) where TEntity : class
{
if (!table.Contains(entity))
{
table.InsertOnSubmit(entity);
}
}

