レコードがまだテーブルに存在しない場合に、レコードを挿入する簡単な方法があるかどうか知りたいです。私はまだ 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;
}