我一直按照本指南中的建议设置SignalR,以便实时向客户端推送数据库更新:
在我的控制器中使用简单的Linq查询时,一切正常:
public async Task<ActionResult> Messages()
{
var collection = db.Messages;
ViewBag.NotifierEntity = db.GetNotifierEntity<Message>(collection).ToJson();
return View(await collection.ToListAsync());
}
但每当我想做一些稍微复杂的事情,比如:
public async Task<ActionResult> Messages()
{
var username = CurrentUser().UserName;
var collection = db.Messages.Where(m => m.Recipients
.All(u => u.UserName == username));
ViewBag.NotifierEntity = db.GetNotifierEntity<Message>(collection).ToJson();
return View(await collection.ToListAsync());
}
我从JavaScriptSerializer收到有关循环引用的错误。我切换到Json.Net序列化器:
public static NotifierEntity FromJson(string value)
{
if (String.IsNullOrEmpty(value))
throw new ArgumentNullException("NotifierEntity Value can not be null.");
//return new JavaScriptSerializer().Deserialize<NotifierEntity>(value);
return JsonConvert.DeserializeObject<NotifierEntity>(value, new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
}
但是现在我在访问该页面时收到以下异常:
[Newtonsoft.Json.JsonSerializationException] {"Error converting value \"p__linq__0\" to type 'System.Data.SqlClient.SqlParameter'. Path 'SqlParameters[0]', line 1, position 1010."}
[InnerException] {"Could not cast or convert from System.String to System.Data.SqlClient.SqlParameter."}
但View本身似乎正确呈现。有人可以帮忙吗?
编辑:值包含以下内容:
"{\"SqlQuery\":\"SELECT \\r\\n 1 AS [C1], \\r\\n [Extent1].[ID] AS [ID], \\r\\n [Extent1].[Date] AS [Date], \\r\\n [Extent1].[Title] AS [Title], \\r\\n [Extent1].[Content] AS [Content], \\r\\n [Extent1].[Read] AS [Read], \\r\\n [Extent1].[Sender_Id] AS [Sender_Id]\\r\\n FROM [dbo].[Messages] AS [Extent1]\\r\\n WHERE NOT EXISTS (SELECT \\r\\n 1 AS [C1]\\r\\n FROM [dbo].[AspNetUsers] AS [Extent2]\\r\\n WHERE ([Extent1].[ID] = [Extent2].[Message_ID]) AND (( NOT (([Extent2].[UserName] = @p__linq__0) AND (0 = (CASE WHEN (@p__linq__0 IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END)))) OR (CASE WHEN ([Extent2].[UserName] = @p__linq__0) THEN cast(1 as bit) WHEN ( NOT (([Extent2].[UserName] = @p__linq__0) AND (0 = (CASE WHEN (@p__linq__0 IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END)))) THEN cast(0 as bit) END IS NULL))\\r\\n )\",\"SqlConnectionString\":\"Data Source=(LocalDb)\\\\MSSQLLocalDB;Initial Catalog=PrismContext;Integrated Security=SSPI;\",\"SqlPa
rameters\":[\"p__linq__0\"]}"
编辑2:GetNotifierEntity定义为:
public static NotifierEntity GetNotifierEntity<TEntity>(this DbContext dbContext, IQueryable iQueryable) where TEntity : EntityBase
{
var objectQuery = dbContext.GetObjectQuery<TEntity>(iQueryable);
return new NotifierEntity()
{
SqlQuery = objectQuery.ToTraceString(),
SqlConnectionString = objectQuery.SqlConnectionString(),
SqlParameters = objectQuery.SqlParameters()
};
}