I want to run a dynamic custom query which is not bound to any object or class in my project. It will always return null or 1 record.
I tried many things but without success so far:
// 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);
}
but I need this with dynamic query on a database view while not adding the model in 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);
}