IQueryable<> 不包含查询的定义 - 检查数据库 C# 中是否存在记录
IQueryable<> does not contain a definition for Query - Checking if record exists in Database C#
我找到了几个主题,但它们没有回答我的问题。
在其他主题答案的帮助下,我得到了如下代码:
private void CheckIfProductExists()
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(
new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
List<Product> myCollection = conn.Table<Product>().ToList<Product>();
IQueryable<Product> query = myCollection.AsQueryable();
var checkProductName = query.Query<Product>(
"SELECT COUNT(*) from [Product] where [Name] like '@name'",
conn);
checkProductName.Parameters.AddWithValue("@name", DescriptionBox.Text);
int ProductExist = checkProductName.ExecuteScalar();
if (ProductExist > 0)
{
//Product exist
}
else
{
//Product doesn't exist.
}
}
}
我在
收到标题中的错误
.Query<Product>
有什么建议我的代码可能有什么问题吗?
您对错误类型的对象调用了 Query
方法。相反,您可以根据 SQLiteConnection
documentation
在 SQLiteConnection
上调用 ExecuteScalar
private void CheckIfProductExists()
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(
new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
int productCount = conn.ExecuteScalar<int>(
"SELECT COUNT(*) from [Product] where [Name] like ?",
DescriptionBox.Text);
if (productCount > 0)
{
//Product exist
}
else
{
//Product doesn't exist.
}
}
}
请注意,现在 like
将取决于添加到 DescriptionBox.Text
的通配符。因此,如果值为 "car",它将只匹配 "car",但如果值为 "car%",它将匹配任何以 "car" 开头的内容。我不确定这是否是您真正想要的。
我找到了几个主题,但它们没有回答我的问题。
在其他主题答案的帮助下,我得到了如下代码:
private void CheckIfProductExists()
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(
new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
List<Product> myCollection = conn.Table<Product>().ToList<Product>();
IQueryable<Product> query = myCollection.AsQueryable();
var checkProductName = query.Query<Product>(
"SELECT COUNT(*) from [Product] where [Name] like '@name'",
conn);
checkProductName.Parameters.AddWithValue("@name", DescriptionBox.Text);
int ProductExist = checkProductName.ExecuteScalar();
if (ProductExist > 0)
{
//Product exist
}
else
{
//Product doesn't exist.
}
}
}
我在
收到标题中的错误.Query<Product>
有什么建议我的代码可能有什么问题吗?
您对错误类型的对象调用了 Query
方法。相反,您可以根据 SQLiteConnection
documentation
SQLiteConnection
上调用 ExecuteScalar
private void CheckIfProductExists()
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(
new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
int productCount = conn.ExecuteScalar<int>(
"SELECT COUNT(*) from [Product] where [Name] like ?",
DescriptionBox.Text);
if (productCount > 0)
{
//Product exist
}
else
{
//Product doesn't exist.
}
}
}
请注意,现在 like
将取决于添加到 DescriptionBox.Text
的通配符。因此,如果值为 "car",它将只匹配 "car",但如果值为 "car%",它将匹配任何以 "car" 开头的内容。我不确定这是否是您真正想要的。