的LINQ to SQL插入 - 如果 - 不存在 [英] LINQ to SQL insert-if-non-existent

查看:112
本文介绍了的LINQ to SQL插入 - 如果 - 不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有插入一条记录,如果它不已经在一个表中存在一个简单的方法。我仍然在试图建立我的LINQ到SQL技能。



下面是我得到了什么,但是看起来应该有一个更简单的方法。

 公共静态TEntity InsertIfNotExists< TEntity> 

的DataContext分贝,
表< TEntity>表,
Func键< TEntity,布尔>其中,
TEntity纪录

,其中TEntity:类
{
TEntity现有= table.SingleOrDefault< TEntity>(其中);

如果(现!= NULL)
{
回报率存在;
}
,否则
{
table.InsertOnSubmit(记录);

//不能使用table.Context.SubmitChanges()
//因为它是只读

db.SubmitChanges();
}

返回记录;
}


解决方案

 公共静态无效InsertIfNotExists< TEntity> 
(此表< TEntity>表,
TEntity实体,
表达式来; Func键< TEntity,布尔>>谓语)
其中TEntity:类
{
如果(!table.Any(谓语))
{
table.InsertOnSubmit(记录);
table.Context.SubmitChanges();
}
}


table.InsertIfNotExists(实体,E => e.BooleanProperty);


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插入 - 如果 - 不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆