@Remus Rusanu 解释得很好。您不能使用TOP
SQL 命令的关键字。但是,如果你想选择一些TOP
数据,你可以使用下面的替代解决方案。
我正在从数据库中选择所有记录,但我只在我的列表中放入了十条记录,并且我将此列表返回到我的仪表板。所以,每次我收到最新的十条记录。
TOP
您可以在没有关键字的情况下使用当前的 SQL 命令。我的是:
SQL 命令:
Select [Id], [Name] FROM dbo.CUSTOMER where InsertDate = @InsertDate ORDER BY [ID] DESC;
然后,在您的应用程序中,您可以根据您的最高计数填写您的列表。
检查我对以下源代码的评论。
public List<CustomerModel> GetAllCustomer()
{
List<CustomerModel> lstCustomerModel = new List<CustomerModel>();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string InsertDate = string.Empty;
InsertDate = DateTime.Now.ToString("yyyyMMdd");
string query = "SELECT [Id] " +
",[Name] " +
"FROM [dbo].[Customer] where InsertDate = " + InsertDate + " ORDER BY [Id] DESC;";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.Text;
cmd.Notification = null;
SqlDependency.Stop(connectionString);
SqlDependency.Start(connectionString);
SqlDependency sqlDependency = new SqlDependency(cmd);
sqlDependency.OnChange += OnDependencyChange;
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
int counter = 0;
while (reader.Read())
{
if (counter == 10) /* Here, I am reading just first ten record. After 10 records, I am not filling my List. So, It is kind of top 10 records.. Alternative solution.*/
break;
counter++;
lstCustomerModel.Add(new CustomerModel
{
Id = Convert.ToInt32(reader.GetValue("Id")),
Name = WeightUnit = reader.GetValue("Name")
});
//break;
}
}
}
}
return lstCustomerModel;
}
private void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
_context.Clients.All.SendAsync("refreshCustomers");
}
}