gpt4 book ai didi

c# - sqlite-net-pcl 中的 InsertAll 和 UpdateAll VS SQLite.Net-PCL 中的 InsertOrReplaceAll

转载 作者:行者123 更新时间:2023-11-30 21:37:31 32 4
gpt4 key购买 nike

我想删除 SQLite.Net-PCL打包并想使用sqlite-net-pcl因为我后来发现SQLite.Net-PCL官方没有维护。

我的 Xamarin 项目中有一些表将 GUID 存储为字符串类型的主键。我有来自服务器的记录列表,目前使用 InsertOrReplaceAll 方法根据我的 GUID 主键插入新记录并更新现有记录。

现在,sqlite-net-pcl 没有 InsertOrReplaceAll 方法,而只有 InsertAllUpdateAll 方法。 Microsoft msdn Link说检查主键是否有可用值,并根据该值决定是否必须插入或更新记录。

但是,我有这样一种情况,在插入或更新对象之前,主键值总是预先设置在 List 中,并且不想循环检查记录是否存在或不超过 500 条记录。

在这种情况下如何一次插入或替换我的所有记录?

考虑以下示例来理解这种情况:

using (var conn = new DBConnectionService().GetConnection())
{
List<ENTEmployee> employees = new List<ENTEmployee>()
{
new ENTEmployee(){ Id = "b977ec04-3bd7-4691-b4eb-ef47ed6796fd", FullName = "AAA BBB", Salary = 15000 },
new ENTEmployee(){ Id = "c670a3e2-b13f-42b3-849c-fd792ebfd103", FullName = "BBB BBB", Salary = 16000 },
new ENTEmployee(){ Id = "d961c33c-0244-48dc-8e10-f4f012386eb6", FullName = "CCC BBB", Salary = 17000 },
new ENTEmployee(){ Id = "35be4508-ff93-4be8-983f-d4908bcc592d", FullName = "DDD BBB", Salary = 18000 },
new ENTEmployee(){ Id = "0875549c-d06c-4983-b89a-edf81b6aa70d", FullName = "EEE BBB", Salary = 19000 },
};

var insertResult = conn.InsertAll(employees);

//Updated Record
employees[0].FullName = "AAA Updated";
employees[0].Salary = 12300;


//New Records
employees.Add(new ENTEmployee() { Id = "87f48ecf-715c-4327-9ef3-11712ba4a120", FullName = "FFF BBB", Salary = 20000 });
employees.Add(new ENTEmployee() { Id = "85f53888-b1e9-460c-8d79-88010f143bcf", FullName = "GGG BBB", Salary = 21000 });

//Now here,
//How to decide which records to be inserted and which records to be updated for List employees?
}

最佳答案

我实现了一个与他们的实现类似的扩展方法。您可以将它与 SQLite.Net-PCL 中的原始版本进行比较 project .

static public class SQLiteConnectionExtensions
{
/// <summary>
/// Inserts all specified objects.
/// For each insertion, if a UNIQUE
/// constraint violation occurs with
/// some pre-existing object, this function
/// deletes the old object.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable" /> of the objects to insert or replace.
/// </param>
/// <returns>
/// The total number of rows modified.
/// </returns>
static public int InsertOrReplaceAll(this SQLiteConnection connection, IEnumerable objects, bool runInTransaction = true)
{
var c = 0;
if (objects == null)
return c;

if (runInTransaction)
{
connection.RunInTransaction(() =>
{
foreach (var r in objects)
{
c += connection.Insert(r, "OR REPLACE", Orm.GetType(r));
}
});
}
else
{
foreach (var r in objects)
{
c += connection.Insert(r, "OR REPLACE", Orm.GetType(r));
}
}

return c;
}
}

关于c# - sqlite-net-pcl 中的 InsertAll 和 UpdateAll VS SQLite.Net-PCL 中的 InsertOrReplaceAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47124476/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com