我想运行一个动态的自定义查询,该查询未绑定到我的项目中的任何对象或类。它将始终返回null或1条记录。
我尝试了很多事情,但到目前为止都没有成功:
// this is working function with hard-coded query
private Dictionary<string, string> getRecord(string id, string viewName)
{
Peron p = db.Person.Where(e => e.ID == id).FirstOrDefault();
var json = JsonConvert.SerializeObject(p);
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
但是我需要在数据库视图上进行动态查询,同时又不将模型添加到EF models.edmx
中。
private Dictionary<string, string> getRecord(string id, string viewName)
{
string qry = "select * from " + viewName + " where ID='" + id + "'";
var p = db.Database.SqlQuery<dynamic>(qry).FirstOrDefault();
// p sometimes returns null on dynamic object, many times it throws
// an error "Cannot convert this to this" ....
var json = JsonConvert.SerializeObject(p);
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}