0

I created four model classes for my database in asp.net, the ideia is to create a model for a Questionnaire, where the Questionnaire has multiple questions, and every question as multiple answers , the answers have 3 types, multi answers where the user only can select one answer, multi answers where the user can select multi answers and finnaly a text answer. A question only has an answer type.

I can insert data in the database but when i do a GET(using postman) to the question table or answers table, i get the following error:

 "Message": "An error has occurred.",
"ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": null,
"InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "Error getting value from 'Questionnaire' on 'System.Data.Entity.DynamicProxies.Question_A710DEFF3886CBDE62F28495FD980EB31736277C66BCA5CDB9DCFB9CD2A69007'.",
    "ExceptionType": "Newtonsoft.Json.JsonSerializationException",
    "StackTrace": "   em Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   em Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   em System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- Fim do rastreio da pilha da localização anterior em que a excepção foi emitida ---\r\n   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   em System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()",
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "An error occurred while executing the command definition. See the inner exception for details.",
        "ExceptionType": "System.Data.Entity.Core.EntityCommandExecutionException",
        "StackTrace": "   em System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)\r\n   em System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)\r\n   em System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()\r\n   em System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n   em System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()\r\n   em System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n   em System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n   em System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n   em System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption)\r\n   em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n   em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n   em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)\r\n   em System.Data.Entity.DynamicProxies.Question_A710DEFF3886CBDE62F28495FD980EB31736277C66BCA5CDB9DCFB9CD2A69007.get_Inqueritov()\r\n   em GetInqueritov(Object )\r\n   em Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "Já existe um DataReader aberto associado a este Command, que tem de ser fechado primeiro.",
            "ExceptionType": "System.InvalidOperationException",
            "StackTrace": "   em System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)\r\n   em System.Data.SqlClient.SqlConnection.ValidateConnectionFor

Tables:

public class TypeAnswerv
{
    public TypeAnswerv()
    {
        Questions=new HashSet<Question>();
    }
    [Key]
    public int TypeAnswerId { get; set; }

    [Required]
    public string TypesAnswer { get; set; }

    public ICollection<Question> Questions { get; set; }

}

public class Answer
{
    [Key]
    public int AnswerId { get; set; }
    [Required]
    public string Answerv { get; set; }

    public virtual Question Question { get; set; }

}


public class Questionnaire
{
    public Questionnaire()
    {
        Questions=new HashSet<Question>();
    }
    [Required]
    [Key]
    public int QuestionnaireId { get; set; }
    [Required]
    public string Name { get; set; }
    public DateTime DateCreation { get; set; }
    public DateTime ExpireDate { get; set; }
    public int ExpireIn { get; set; }

    public ICollection<Question> Questions { get; set; }
}

public class Question

{
    public Question()
    {
        Answers=new HashSet<Answer>();
    }

    [Key]
    public int QuestionId { get; set; }

    public string Questionv { get; set; }

    public ICollection<Answer> Answers { get; set; }

    public virtual TypeAnswerv TypeAnswer { get; set; }

    public virtual Questionnaire Questionnaire { get; set; }
}

Controllers:

Answer controller:

public class AnswersController : ApiController
{
    private QuestionarioContext db = new QuestionarioContext();

    // GET: api/Answers
    public IQueryable<Answer> GetAnswers()
    {
        return db.Answers;
    }

    // GET: api/Answers/5
    [ResponseType(typeof(Answer))]
    public async Task<IHttpActionResult> GetAnswer(int id)
    {
        Answer answer = await db.Answers.FindAsync(id);
        if (answer == null)
        {
            return NotFound();
        }

        return Ok(answer);
    }

    // PUT: api/Answers/5
    [ResponseType(typeof(void))]
    public async Task<IHttpActionResult> PutAnswer(int id, Answer answer)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != answer.AnswerId)
        {
            return BadRequest();
        }

        db.Entry(answer).State = EntityState.Modified;

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!AnswerExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Answers
    [ResponseType(typeof(Answer))]
    public async Task<IHttpActionResult> PostAnswer(Answer answer)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Answers.Add(answer);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = answer.AnswerId }, answer);
    }

    // DELETE: api/Answers/5
    [ResponseType(typeof(Answer))]
    public async Task<IHttpActionResult> DeleteAnswer(int id)
    {
        Answer answer = await db.Answers.FindAsync(id);
        if (answer == null)
        {
            return NotFound();
        }

        db.Answers.Remove(answer);
        await db.SaveChangesAsync();

        return Ok(answer);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool AnswerExists(int id)
    {
        return db.Answers.Count(e => e.AnswerId == id) > 0;
    }
}

Question controller:

 public class QuestionsController : ApiController
{
    private QuestionarioContext db = new QuestionarioContext();

    // GET: api/Questions
    public IQueryable<Question> GetQuestions()
    {
        return db.Questions;
    }

    // GET: api/Questions/5
    [ResponseType(typeof(Question))]
    public async Task<IHttpActionResult> GetQuestion(int id)
    {
        Question question = await db.Questions.FindAsync(id);
        if (question == null)
        {
            return NotFound();
        }

        return Ok(question);
    }

    // PUT: api/Questions/5
    [ResponseType(typeof(void))]
    public async Task<IHttpActionResult> PutQuestion(int id, Question question)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != question.QuestionId)
        {
            return BadRequest();
        }

        db.Entry(question).State = EntityState.Modified;

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!QuestionExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Questions
    [ResponseType(typeof(Question))]
    public async Task<IHttpActionResult> PostQuestion(Question question)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Questions.Add(question);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = question.QuestionId }, question);
    }

    // DELETE: api/Questions/5
    [ResponseType(typeof(Question))]
    public async Task<IHttpActionResult> DeleteQuestion(int id)
    {
        Question question = await db.Questions.FindAsync(id);
        if (question == null)
        {
            return NotFound();
        }

        db.Questions.Remove(question);
        await db.SaveChangesAsync();

        return Ok(question);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool QuestionExists(int id)
    {
        return db.Questions.Count(e => e.QuestionId == id) > 0;
    }
}
8
  • where is the code that actually does the query that is breaking? Commented Jul 12, 2017 at 15:34
  • I am using postaman to test. Commented Jul 12, 2017 at 15:36
  • The problem is not with your models, but your controller action. Show that code. Looks like you haven't closed the datareader by using .ToList() or .ToArray() etc. Commented Jul 12, 2017 at 15:37
  • The controllers were generated automatically by the visual studio 2017 using the models. Commented Jul 12, 2017 at 15:41
  • I'd suspect something in the area of either the async and/or controller disposal. See here and here. BTW, you should add the stuff below to the original question - not as an answer. Commented Jul 12, 2017 at 17:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.