LINQ to SQL insert-if-non-existent(LINQ to SQL insert-if-non-existent)
本文介绍了LINQ to SQL insert-if-non-existent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果表中不存在记录,我想知道是否有更简单的方法来插入记录.我仍在努力培养我的 LINQ to SQL 技能.
I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills.
这是我所知道的,但似乎应该有更简单的方法.
Here's what I've got, but it seems like there should be an easier way.
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);
这篇关于LINQ to SQL insert-if-non-existent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:LINQ to SQL insert-if-non-existent


基础教程推荐
猜你喜欢
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 创建属性设置器委托 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01