【问题标题】:SQLLITE-Xamarin Form - How to check if a value already existSQLITE-Xamarin Form - 如何检查一个值是否已经存在
【发布时间】:2021-04-20 01:52:32
【问题描述】:

我想检查一个值是否已经存在,如果存在则返回真如果不假。但是,我可能在逻辑上遗漏了一些东西,因为即使值存在也总是返回 null

样本

public bool ExistPref(int userid)
        {
            var result = prefDB.db.Table<notificationsPreferences>().Where(t => t.UserId == userid).FirstOrDefault();
            Console.WriteLine("user exist "+result+userid);
            return result != null;

        }

如果用户存在 我想更新他的记录,否则插入新值

public int UpdateNotifications(notificationsPreferences item)
        {

            if (item.UserId != 0)
            {
                return prefDB.db.Update(item);
            }
            
            else
            {
              return  prefDB.db.Insert(item);

问题出在这里 ** ID 出现在对象项中,但是由于某种原因没有保存 4 位数字 id,保存的是例如 4,我认为这是我添加此项目的时间?/ 那是为什么我的结果总是错误的,因为它没有保存真实的 id。

            }
        }

【问题讨论】:

  • 您的商品 ID 是什么类型,您是否将其标记为“自动增量”?

标签: c# sqlite xamarin.forms


【解决方案1】:

使用Any

return prefDB.db.Table<notificationsPreferences>().Any(t => t.UserId == userid);

【讨论】:

  • 我在代码中添加了一条新注释。我认为我的问题是当我保存项目时,没有保留对象 --item 附带的真实 ID 号。它随机保存一个 3 /4
【解决方案2】:

如果用户存在,我想更新他的记录,否则插入新值

如果你想在sqlite中插入新记录或更新记录,你可以看看下面的代码:

private void insertorupdate(User model)
    {
        var data = _SQLiteConnection.Table<User>();

        var d1 = data.Where(x => x.userId == model.userId).FirstOrDefault();
        if (d1 == null)
        {
            _SQLiteConnection.Insert(model);
            Console.WriteLine("Sucessfully Added");
        }
        else
        {
            Console.WriteLine("Already Mail id Exist");
             _SQLiteConnection.Update(model);
        }
    }

 public class User
{
    [PrimaryKey, AutoIncrement]
    public int userId { get; set; }
    public string userName { get; set; }      
    public string password { get; set; }

   
}

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 2023-01-28
    • 1970-01-01
    • 2011-04-17
    • 2019-08-22
    • 2010-09-08
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多