我正在关注THIS EXAMPLE
它按预期工作,一切正常。
问题在以下代码中:
public class MessagesRepository
{
public IEnumerable<Messages> GetAllMessages()
{
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["SEPRETEntities"].ConnectionString);
string _connString = efBuilder.ProviderConnectionString;
var messages = new List<Messages>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(@"SELECT [Id],[Name],[Active],[TimeCreated],[TimeUpdated] FROM [dbo].[Method]", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{ messages.Add(item: new Method { Id = (long) reader["Id"], Name = (string)reader["Name"], Active = (bool)reader["Active"], TimeCreated = Convert.ToDateTime(reader["TimeCreated"]) });
}
}
}
return messages;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MessagesHub.SendMessages();
}
}
}
问题是我根本不喜欢在wile(reader.Read())上创建列表的方式...我觉得这很讨厌代码,而且太大了。
所以我尝试使用LINQ来简化事情,这就是结果:
public IEnumerable<Method> GetData()
{
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["SEPRETEntities"].ConnectionString);
string _connString = efBuilder.ProviderConnectionString;
using (SEPRETEntities DBC = new SEPRETEntities())
{
// HERE IS HOW I'D LIKE TO CREATE THE LIST USING LINQ, A SIMPLER WAY
List<Method> methods = DBC.Methods.ToList();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(@"SELECT [Id],[Name],[Active],[TimeCreated],[TimeUpdated] FROM [dbo].[Method]", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(Dependency_OnChange);
}
}
return methods;
}
但是该项目无法正常运行。它停止处理表格上的更改,并且不再实时更新。
所以我的问题是否有办法实现?我的意思是使用LINQ可以使“方法”表的列表更容易,而无需项目按预期停止运行
我当时在Google上搜索时根本没有运气,几乎所有示例都使用了很长的路(while(reader.Read()等...)。
我认为问题主要出在vardependent = new SqlDependency(command);部分。但是我不知道如何将SqlDependency与LINQ查询以及与数据库的实体连接一起使用。
感谢阅读,祝您愉快。