如何在LINQ中表示sql exists()命令

时间:2010-10-20 01:19:34

标签: c# linq-to-sql

我有一个SQL问题,我一遍又一遍地使用,但现在我需要在LINQ中做更多的事情。我该怎么做呢?是否有将您的sql转换为linq的网站?

conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
//query
command.Parameters.Add(new SqlParameter("@email", email));

//else
command.CommandText = "if exists(SELECT pk_email FROM MyTable WHERE pk_email = @email) begin " +
                "UPDATE MyTable SET last_login = getdate(), is_logged_in = 'true' WHERE pk_email = @email; " +
                "end else begin " +
                "INSERT INTO MyTable (pk_email, last_login, is_logged_in) VALUES (@email , getdate(), 'true'); " +
                "end";
command.ExecuteNonQuery();

3 个答案:

答案 0 :(得分:1)

你可以做这样的事情

if(From emails In MyTable Where emails.pk_email == email).Any) {
    'Then update your data here
}
else {
     'Insert your data
}

如果您需要有关插入或datacontext更新的帮助,请删除注释。

答案 1 :(得分:0)

这样的东西?那么这会对数据库造成多少打击呢?通过使用linq,它可以为sql注入提供更多保护吗?

App_DAL.DataDataContext h = new App_DAL.DataDataContext();
if ((from emails in MyTables where emails.pk_email == email select emails.pk_email).Any()) {
    //Then update your data here
    var messenger = (from emails in MyTables where emails.pk_email == email select emails).Single();
    messenger.last_login = DateTime.Now;
    messenger.is_logged_in = true;
    h.SubmitChanges();
}
else 
{
    //Insert your data
    App_DAL.MyTable msg = new App_DAL.MyTable();
    msg.pk_email = email;
    msg.is_logged_in = true;
    msg.last_login = DateTime.Now;
    h.MyTables.InsertOnSubmit(msg);
    h.SubmitChanges();

}

答案 2 :(得分:0)

在实体框架中,我通常使用以下扩展方法来实现您想要的功能(请参阅注释以获取示例)。

/// <summary>
    /// Updates and entity and save it to the database.
    /// If it doesn't exist it creates a new entity and saves it to the database.
    /// <example>
    ///     <code>
    ///         //Updates or inserts a row into Account. The inserted/updated row will have its AccountNumber set to "17".
    ///         var account = db.Accounts.InsertOrUpdate(a => a.ID == id, a => a.AccountNumber = "17");
    ///     </code>
    /// </example>
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="allEntities"></param>
    /// <param name="entityFilter"></param>
    /// <param name="propertySetter"></param>
    /// <returns></returns>
    public static TEntity InsertOrUpdate<TEntity>(this ObjectSet<TEntity> allEntities, Func<TEntity, bool> entityFilter,
                                                  Action<TEntity> propertySetter) where TEntity : class, new()
    {
        //First we use the entityValueMapper to search for an existing entity.
        var entity = allEntities.Where(entityFilter).FirstOrDefault();
        if (entity == null)
        {
            entity = new TEntity();
            allEntities.AddObject(entity);
        }
        propertySetter(entity);
        allEntities.Context.SaveChanges();
        return entity;
    }