Entity Framework .Include

Topics: Web Api
Dec 25, 2011 at 6:09 AM

I'm having an issue when I do a .Include inside of a Get Method which I've pasted below. I'm using Entity Framework 4.2 Code First. For some reason the .Include seems to make this code execute more then one time. Any help would be much appreciated.

[WebGet(UriTemplate = "{id}")]
public HttpResponseMessage<AssessmentTemplate> GetById(int Id)
{
    _logger.Info("Getting AssessmentTemplates");

    var assmentConfig = context.AssessmentTemplates.Include(at => at.AssessmentConfig).Where(at => at.Id == Id).FirstOrDefault();
    
    var response = new HttpResponseMessage<AssessmentTemplate>(assmentConfig, HttpStatusCode.OK);

    return response;
}

Jan 9, 2012 at 7:08 PM

I actually found out what was going on here, thanks to some other sites.

The fact that a proxy is used when using the .Include causes an issue with serialization.

The fix was just to add this before

 

context.Configuration.ProxyCreationEnabled = false;

var assmentConfig = context.AssessmentTemplates.Include(at => at.AssessmentConfig).Where(at => at.Id == Id).FirstOrDefault();