gpt4 book ai didi

c# - LINQ to SQL insert-if-non-existent

转载 作者:可可西里 更新时间:2023-11-01 08:31:51 24 4
gpt4 key购买 nike

我想知道是否有更简单的方法来插入表中尚不存在的记录。我仍在努力培养我的 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);

关于c# - LINQ to SQL insert-if-non-existent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/100068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com