我是Asp .Net平台的学生开发人员。根据我的研究,使用Asp.Net可以实现实时数据库。这就是为什么我知道我需要使用SignalR的原因。在我的示例中,我尝试构建它,但是在从SQL Server提取数据时遇到了An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
这样的错误。我不是专业人士,也不知道问题出在哪里或问题出在哪里。许多来源不清楚,以供学生在建立实时数据库问题中理解。您能帮我解决这个问题吗?也许您的答案可能是像我这样的学生的榜样。谢谢。
这是我的控制器:
public string GetAllMessages()
{
DatabaseProcess dbp = new DatabaseProcess();
var messages = dbp.GetMessages();
return Helper.RazorViewRender(messages, "~/Views/Shared/_MessagesList.cshtml");
}
这是我的数据库处理类,用于获取数据:
public class DatabaseProcess
{
public IEnumerable<textMessageModel> GetMessages()
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AgmProvider"].ConnectionString))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlCommand cmd = new SqlCommand(@"SELECT [textId], [textOwner], [textContent], [groupFk],[textDate] from [dbo].[TextMessage]", connection))
{
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
using (SqlDataReader dr = cmd.ExecuteReader()) // Error Line
{
List<textMessageModel> Messages = new List<textMessageModel>();
while (dr.Read())
{
Messages.Add(new textMessageModel
{
textOwner = dr["textOwner"].ToString(),
textId = Convert.ToInt32(dr["textId"].ToString()),
textContent = dr["textContent"].ToString(),
groupFk = Convert.ToInt32(dr["groupFk"].ToString()),
textDate= Convert.ToDateTime(dr["textDate"]),
});
}
return Messages;
}
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
TextMessage.Show();
}
}
我的cshtml用于显示数据:
<script src="~/scripts/jquery-3.0.0.min.js"></script>
<script src="~/scripts/jquery.signalR-2.0.3.min.js"></script>
<script src="~/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var pers = $.connection.textMessageHub;
pers.client.trigger = function () {
getData();
};
$.connection.hub.start();
getData();
});
function getData() {
var tbl = $('#msgList');
$.ajax({
url: '@Url.Action("GetMessages", "Home")',
type: 'GET',
datatype: 'json',
success: function (data) {
tbl.html(data);
}
});
}
</script>
</head>
<body>
<div id="msgList">
</div>
</body>
</html>