Web-API display problem with tables with relationships

0

Good morning, people,

I am developing a WEB API to be consumed in a mobile application using Xamarin, I am transposing the classes directly from the database with the code first of Visual Studio, however when I try to generate a simple view of the Players listing the following error appears

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>Ocorreu um erro.</Message>
<ExceptionMessage>
O tipo 'ObjectContent'1' não pôde serializar o corpo da resposta para o tipo de conteúdo 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>Ocorreu um erro.</Message>
<ExceptionMessage>
An error occurred while preparing the command definition. See the inner exception for details.
</ExceptionMessage>
<ExceptionType>
System.Data.Entity.Core.EntityCommandCompilationException
</ExceptionType>
<StackTrace>
em System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory) em System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext) em System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext) em System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.CreateCommandDefinition(ObjectContext context, DbQueryCommandTree tree) em System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable'1 compiledQueryParameters, AliasGenerator aliasGenerator) em System.Data.Entity.Core.Objects.EntitySqlQueryState.GetExecutionPlan(Nullable'1 forMergeOption) em System.Data.Entity.Core.Objects.ObjectQuery'1.<>c__DisplayClass7.<GetResults>b__6() em System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func'1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) em System.Data.Entity.Core.Objects.ObjectQuery'1.<>c__DisplayClass7.<GetResults>b__5() em System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func'1 operation) em System.Data.Entity.Core.Objects.ObjectQuery'1.GetResults(Nullable'1 forMergeOption) em System.Data.Entity.Core.Objects.ObjectQuery'1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() em System.Data.Entity.Internal.LazyEnumerator'1.MoveNext() em WriteArrayOfJogadorToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) em System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) em System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) em System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) em System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) em System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) em System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) em System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) em System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) em System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada --- em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) em System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__22.MoveNext()
</StackTrace>
<InnerException>
<Message>Ocorreu um erro.</Message>
<ExceptionMessage>
(6,10) : error 3015: Problem in mapping fragments starting at lines 6, 15: Foreign key constraint 'Atributos_HabilidadesFiltros' from table HabilidadesFiltros (ID_Jogo, ID_Atributo) to table Atributos (ID_Atributos, ID_Jogo):: Insufficient mapping: Foreign key must be mapped to some AssociationSet or EntitySets participating in a foreign key association on the conceptual side.
</ExceptionMessage>
<ExceptionType>System.Data.Entity.Core.MappingException</ExceptionType>
<StackTrace>
em System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(EntityContainerMapping entityContainerMap, Dictionary'2 resultDictionary) em System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews(EntityContainer container) em System.Data.Entity.Core.Common.Utils.Memoizer'2.<>c__DisplayClass2.<Evaluate>b__0() em System.Data.Entity.Core.Common.Utils.Memoizer'2.Result.GetValue() em System.Data.Entity.Core.Common.Utils.Memoizer'2.Evaluate(TArg arg) em System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace, StorageMappingItemCollection storageMappingItemCollection) em System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetGeneratedView(EntitySetBase extent) em System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ExpandView(ScanTableOp scanTableOp, IsOfOp& typeFilter) em System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ProcessScanTable(Node scanTableNode, ScanTableOp scanTableOp, IsOfOp& typeFilter) em System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(ScanTableOp op, Node n) em System.Data.Entity.Core.Query.InternalTrees.ScanTableOp.Accept[TResultType](BasicOpVisitorOfT'1 v, Node n) em System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT'1.VisitNode(Node n) em System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) em System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n) em System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n) em System.Data.Entity.Core.Query.InternalTrees.ProjectOp.Accept[TResultType](BasicOpVisitorOfT'1 v, Node n) em System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT'1.VisitNode(Node n) em System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) em System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n) em System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitPhysicalOpDefault(PhysicalOp op, Node n) em System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT'1.Visit(PhysicalProjectOp op, Node n) em System.Data.Entity.Core.Query.InternalTrees.PhysicalProjectOp.Accept[TResultType](BasicOpVisitorOfT'1 v, Node n) em System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT'1.VisitNode(Node n) em System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(Dictionary'2& tvfResultKeys) em System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(PlanCompiler planCompilerState, StructuredTypeInfo& typeInfo, Dictionary'2& tvfResultKeys) em System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Compile(List'1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set'1& entitySets) em System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Compile(DbCommandTree ctree, List'1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set'1& entitySets) em System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)
</StackTrace>
</InnerException>
</InnerException>
</Error>

below follows the model of the bank

FollowtheclassI'mlisting

namespace WebApplication2.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Jogador")]
    public partial class Jogador
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Jogador()
        {
            HabilidadesFiltros = new HashSet<HabilidadesFiltros>();
            JogosCadastrados = new HashSet<JogosCadastrados>();
        }

        [Key]
        public short ID_Jogador { get; set; }

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

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

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

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HabilidadesFiltros> HabilidadesFiltros { get; set; }

        public virtual LeagueOfLegends LeagueOfLegends { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<JogosCadastrados> JogosCadastrados { get; set; }
    }
}

I'm trying to get the first method to get the <

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class JogadorController : ApiController
    {
        private Context db = new Context();

        // GET: api/Jogador
        public IQueryable<Jogador> GetJogador()
        {
            return db.Jogador;
        }

        // GET: api/Jogador/5
        [ResponseType(typeof(Jogador))]
        public IHttpActionResult GetJogador(short id)
        {
            Jogador jogador = db.Jogador.Find(id);
            if (jogador == null)
            {
                return NotFound();
            }

            return Ok(jogador);
        }

        // PUT: api/Jogador/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutJogador(short id, Jogador jogador)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != jogador.ID_Jogador)
            {
                return BadRequest();
            }

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

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!JogadorExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Jogador
        [ResponseType(typeof(Jogador))]
        public IHttpActionResult PostJogador(Jogador jogador)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Jogador.Add(jogador);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = jogador.ID_Jogador }, jogador);
        }

        // DELETE: api/Jogador/5
        [ResponseType(typeof(Jogador))]
        public IHttpActionResult DeleteJogador(short id)
        {
            Jogador jogador = db.Jogador.Find(id);
            if (jogador == null)
            {
                return NotFound();
            }

            db.Jogador.Remove(jogador);
            db.SaveChanges();

            return Ok(jogador);
        }

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

        private bool JogadorExists(short id)
        {
            return db.Jogador.Count(e => e.ID_Jogador == id) > 0;
        }
    }
}

Finally, the context class that references foreign keys

namespace WebApplication2.Models
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

    public partial class Context : DbContext
    {
        public Context()
            : base("name=Context")
        {
        }

        public virtual DbSet<Atributos> Atributos { get; set; }
        public virtual DbSet<HabilidadesFiltros> HabilidadesFiltros { get; set; }
        public virtual DbSet<Jogador> Jogador { get; set; }
        public virtual DbSet<JogosCadastrados> JogosCadastrados { get; set; }
        public virtual DbSet<LeagueOfLegends> LeagueOfLegends { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Atributos>()
                .Property(e => e.Nome_Atributo)
                .IsUnicode(false);

            modelBuilder.Entity<Atributos>()
                .HasMany(e => e.HabilidadesFiltros)
                .WithRequired(e => e.Atributos)
                .HasForeignKey(e => new { e.ID_Atributo, e.ID_Jogo })
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<HabilidadesFiltros>()
                .Property(e => e.Valor)
                .IsUnicode(false);

            modelBuilder.Entity<Jogador>()
                .Property(e => e.Nome)
                .IsUnicode(false);

            modelBuilder.Entity<Jogador>()
                .Property(e => e.Email)
                .IsUnicode(false);

            modelBuilder.Entity<Jogador>()
                .Property(e => e.Senha)
                .IsUnicode(false);

            modelBuilder.Entity<Jogador>()
                .HasMany(e => e.HabilidadesFiltros)
                .WithRequired(e => e.Jogador)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Jogador>()
                .HasOptional(e => e.LeagueOfLegends)
                .WithRequired(e => e.Jogador);

            modelBuilder.Entity<Jogador>()
                .HasMany(e => e.JogosCadastrados)
                .WithMany(e => e.Jogador)
                .Map(m => m.ToTable("JogosJogador").MapLeftKey("ID_Jogador").MapRightKey("ID_Jogos"));

            modelBuilder.Entity<JogosCadastrados>()
                .Property(e => e.Nome_Jogo)
                .IsUnicode(false);

            modelBuilder.Entity<JogosCadastrados>()
                .Property(e => e.Genero)
                .IsUnicode(false);

            modelBuilder.Entity<JogosCadastrados>()
                .Property(e => e.Plataforma)
                .IsUnicode(false);

            modelBuilder.Entity<JogosCadastrados>()
                .HasMany(e => e.Atributos)
                .WithRequired(e => e.JogosCadastrados)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<JogosCadastrados>()
                .HasMany(e => e.HabilidadesFiltros)
                .WithRequired(e => e.JogosCadastrados)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<LeagueOfLegends>()
                .Property(e => e.Nick)
                .IsUnicode(false);

            modelBuilder.Entity<LeagueOfLegends>()
                .Property(e => e.Nivel)
                .IsUnicode(false);

            modelBuilder.Entity<LeagueOfLegends>()
                .Property(e => e.Elo)
                .IsUnicode(false);

            modelBuilder.Entity<LeagueOfLegends>()
                .Property(e => e.Posição)
                .IsUnicode(false);

            modelBuilder.Entity<LeagueOfLegends>()
                .Property(e => e.Nivel_Filtro)
                .IsUnicode(false);

            modelBuilder.Entity<LeagueOfLegends>()
                .Property(e => e.Elo_Filtro_De)
                .IsUnicode(false);

            modelBuilder.Entity<LeagueOfLegends>()
                .Property(e => e.Posicao_Filtro)
                .IsUnicode(false);

            modelBuilder.Entity<LeagueOfLegends>()
                .Property(e => e.Elo_Filtro_Ate)
                .IsUnicode(false);
        }
    }
}
    
asked by anonymous 22.05.2018 / 15:25

0 answers