如何在web api中设置通用集合以进行序列化? 我有课程
public partial class User:BaseEntity
{
[Required,MaxLength(100), MinLength(5)]
[Index(IsUnique = true)]
public string Login { get; set; }
[Required, MaxLength(100), MinLength(64)]
public byte[] Password { get; set; }
[MaxLength(100),MinLength(5)]
[EmailAddress]
[Index(IsUnique=true)]
public string Email { get; set; }
[MaxLength(40), MinLength(4)]
[Index(IsUnique = true)]
public string NickName { get; set; }
[MaxLength(100), MinLength(4)]
public string FullName { get; set; }
public virtual ICollection<Group> Groups { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
public class UsersController : ApiController
{
public IEnumerable<User> GetAllUser()
{
using (var repoProvider = new RepositoryProvider())
{
return repoProvider.Get<UserRepository>().GetAll();
}
}
}
我们如何看待用户拥有通用集合属性。当我尝试启动应用程序时出现此错误
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>Type 'System.Data.Entity.DynamicProxies.Users_0D7A537351492F8D419F58EA70B1240500CF0FFF354951D83FA225EA973C5338' with data contract name
'Employee_0D7A537351492F8D419F58EA70B1240500CF0FFF354951D83FA225EA973C5338:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not
expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute
attribute or by adding them to the list of known types passed to DataContractSerializer.</ExceptionMessage>
<ExceptionType>System.Runtime.Serialization.SerializationException</ExceptionType>
如何解决此问题?
答案 0 :(得分:1)
问题可能有两个原因
您在EF中启用了动态代理,并且您向浏览器发送了一个实体,该实体没有原始类型Users
,但是您可以看到名称很长的动态类在异常消息中:Users_0D7A53..
实体未配置为使用DataContractSerializer
进行(反)序列化(即不可序列化)
第一种解决方案是在EF上禁用动态代理创建,或在查询中使用AsNoTracking
扩展方法来避免生成代理。
相关文档:
第二部分不太可能成为问题的根源。要解决此问题,基本上您可以使用序列化属性:[DataContract]
,[DataMember]
等。