Cannot read data by Entity Framework 6 using IIS10

asp.net-mvc asp.net-mvc-5 entity-framework entity-framework-6 iis-10

Question

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.

1
0
8/25/2018 9:41:23 AM

Popular Answer

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.

0
8/27/2018 5:21:22 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow