asp.net中

时间:2017-07-12 15:31:55

标签: asp.net sql-server entity-framework

我在asp.net中为我的数据库创建了四个模型类,ideia是为问卷调查创建模型,其中调查问卷有多个问题,每个问题都是多个答案,答案有3种类型,多个答案在哪里用户只能选择一个答案,多个答案,用户可以选择多个答案,并完成文本答案。一个问题只有答案类型。

我可以在数据库中插入数据但是当我对问题表或答案表进行GET(使用邮递员)时,我收到以下错误:

 "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

表格

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; }
}

控制器:

答案控制器:

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;
    }
}

问题控制员:

 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;
    }
}

0 个答案:

没有答案