efcore icon indicating copy to clipboard operation
efcore copied to clipboard

XmlSerializer Exception

Open simonare opened this issue 7 years ago • 2 comments

XML Serialization does not work for the the query below:

        AddQuestionVM result = await _dbContext.Posts.Where(x => x.Id == questionId)
            .Select(x => new AddQuestionVM
            {
                Id = x.Id,
                Body = x.Body,
                Tags = x.Tags,
                Title = x.Title,
                Answer = x.ChildPosts.Select(answer => new AnswerVM()
                {
                    Id = answer.Id,
                    Body = answer.Body,
                    QuestionId = x.Id
                })
            }).SingleOrDefaultAsync(cancellationToken);

If I change query to

        AddQuestionVM result = await _dbContext.Posts.Where(x => x.Id == questionId)
            .Select(x => new AddQuestionVM
            {
                Id = x.Id,
                Body = x.Body,
                Tags = x.Tags,
                Title = x.Title,
                Answer = x.ChildPosts.Select(answer => new AnswerVM()
                {
                    Id = answer.Id,
                    Body = answer.Body,
                    QuestionId = x.Id
                }).ToList() <-- See here
            }).SingleOrDefaultAsync(cancellationToken);

It works However this is not expected behavior. Json serializer works perfectly fine however XmlSerializer gives error.

Models

public class AddQuestionVM
{
    public AddQuestionVM()
    {
        
    }

    public Guid Id { get; set; }

    /// <summary>
    /// Question Title
    /// </summary>
    [StringLength(200, MinimumLength = 30)]
    [Required]
    public string Title { get; set; }

    /// <summary>
    /// Question Body
    /// </summary>
    [Required]
    public string Body { get; set; }
    
    /// <summary>
    /// Question Tag
    /// </summary>
    [Required]
    [EnsureBetween(1, Maximum = 5)]
    public IList<string> Tags { get; set; }

    /// <summary>
    /// Answer Model
    /// </summary>
    public IEnumerable<AnswerVM> Answer { get; set; }

    /// <summary>
    /// Question Owner
    /// </summary>
    public String OwnerUserId { get; set; }
}

[DataContract]
public class AnswerVM
{
    public AnswerVM()
    {
        
    }

    /// <summary>
    /// Answer Id
    /// </summary>
    [DataMember]
    public Guid? Id { get; set; }

    /// <summary>
    /// Question Id
    /// </summary>
    [DataMember]
    public Guid QuestionId { get; set; }

    /// <summary>
    /// Answer Body
    /// </summary>
    [Required]
    [DataMember]
    public string Body { get; set; }
}

Exception Details:

Type

'Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+EnumerableAdapter`1[WestCore.Module.Faq.Models.Question.AnswerVM]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.

at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.DataContract.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.XmlObjectSerializerContext.GetDataContractSkipValidation(Int32 typeId, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle) at WriteAddQuestionVMToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract ) at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at Microsoft.AspNetCore.Mvc.Formatters.XmlDataContractSerializerOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) at Microsoft.AspNetCore.Mvc.Formatters.XmlDataContractSerializerOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) at Microsoft.AspNetCore.Mvc.Formatters.XmlDataContractSerializerOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)

Further technical details

EF Core version: 2.2.6 Database provider: Devart.Data.Oracle 9.8.838 , Devart.Data.Oracle.EFCore 9.8.838 Target framework: .NET Core 3.0 Operating system: Windows Server 2012 & Windows 10 IDE: Visual Studio 2019 16.3.5

simonare avatar Nov 13 '19 09:11 simonare

@simonare This is likely to have been fixed in the 3.0.0 release since the way projected navigation collections are treated has changed considerably. Can you please try against the 3.0.0 or 3.1.0 preview release and see if you still hit this issue.

ajcvickers avatar Nov 14 '19 21:11 ajcvickers

EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.

BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.

ajcvickers avatar Nov 22 '19 22:11 ajcvickers