简体   繁体   English

WebApi无法序列化实体框架实体

[英]WebApi can't serialize Entity Framework entities

I'm working on a WebApi project and I want to serialize a List<User> and send it back to the user. 我正在研究WebApi项目,我想序列化List<User>并将其发送回用户。 But it just returns [{"$id":"1"}] where User is an entity which was generated by Entity Framework database-first models classes. 但是它只返回[{"$id":"1"}] ,其中User是由Entity Framework数据库优先模型类生成的实体。

Controller: 控制器:

public List<User> GetAllUsers() 
{ 
   List<User> Users = Common.Framework.Persistence.PersistSvr<Business.Entity.User>
                     .GetAll().ToList(); 
  return Users; 
}

Here is the User class: 这是User类:

 public partial class User
 {
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
      public User()
      {
          this.ContentLikes = new HashSet<ContentLikes>();
          this.ContentPermission = new HashSet<ContentPermission>();
          this.File = new HashSet<File>();
          this.FolderPermission = new HashSet<FolderPermission>();
          this.SiteUsers = new HashSet<SiteUsers>();
          this.UserGroup = new HashSet<UserGroup>();
      }

      public long ID { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string Email { get; set; }
      public string UserName { get; set; }
      public string Password { get; set; }
      public Nullable<long> DiskUsed { get; set; }
      public Nullable<long> DiskUsage { get; set; }
      public Nullable<bool> Status { get; set; }

      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<ContentLikes> ContentLikes { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<ContentPermission> ContentPermission { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<File> File { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<FolderPermission> FolderPermission { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<SiteUsers> SiteUsers { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ICollection<UserGroup> UserGroup { get; set; }
 }

I have added these lines of codes to WebApiConfig.cs File. 我已将这些代码行添加到WebApiConfig.cs文件中。

 var json = config.Formatters.JsonFormatter;
 json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
 config.Formatters.Remove(config.Formatters.XmlFormatter);

it just resolved double serialization. 它只是解决了双重序列化。 and i have my old problem. 而且我有老问题。 i will receive $id : "1" when i send a request to my ActionMethod. 当我向ActionMethod发送请求时,我将收到$id : "1"

i have learned that it's because of EntityFramework. 我了解到这是因为EntityFramework。 because WebApi doesn't able to serialize an EntityFramework Entity (i think it's because of relations that exists in my Models) 因为WebApi无法序列化EntityFramework实体(我认为是因为我的模型中存在关系)

so what should i do to solve it ? 那我该怎么解决呢? I don't want to rewrite them all. 我不想全部重写。

Try this 尝试这个

public IHttpActionResult GetAllUsers()
        {
            try
            {
                List<User> Users = Common.Framework.Persistence.PersistSvr<Business.Entity.User>
                                   .GetAll().ToList(); 
                return Ok(Users);

            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.Message);

            }
        }

You will get response in users as json along with status code. 您将以json的形式在用户中获得响应以及状态码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM