An Asp.net MVC 5 web app with Entity Framework 6, is published and hosted on IIS 10.
After publishing, I am able to login and register using build-in MVC services. However, accessing data by EF in db table all return empty results and adding exception would not throw any exception.
IQueryable<Record> records=null;
try
{
records= from m in _context.Record
select m;
}
catch (NullReferenceException e)
{
return Json(JsonConvert.SerializeObject(e.Message, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
}
catch (ArgumentNullException e)
{
return Json(JsonConvert.SerializeObject(e.Message, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
}
catch (Exception e)
{
return Json(JsonConvert.SerializeObject(e, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
}
return Json(JsonConvert.SerializeObject(records, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
Would glad to know any security setting can resolve.
Start simpler, and use the debugger.
var query = _context.Records.AsQueryable();
var records = query.ToList();
return Json(records, JSonRequestBehavior.AllowGet);
if you prefer the linq syntax:
var query = from r in _context.Records
select r;
... put a break point on var records = query.ToList();
and verify you are getting results. If you're getting results, then the issue may be feeding the IQueryable
to Json. If you're still not getting results then double-check your connection string.
My recommendation is to avoid passing entities back to view logic, it's just fraught with issues that crop up with lazy loading and dealing with disconnected entities and re-associating entities with DbContexts on the round trip. I use entities for domain mapping, and view models for data representations for the view. The benefit is avoiding the above lazy-load, etc. issues, but also from a data over the wire perspective you typically don't need to send every value and child reference for each entity. View models reflect the data the view needs, and can be flattened as necessary from the domain.
var viewModels = _context.Records
.Select(x => new RecordViewModel
{
RecordId = x.RecordId,
//...
}).ToList();
return Json(viewModels, JSonRequestBehavior.AllowGet);
You can utilize Automapper for instance to help manage the mapping between entity and view model.