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

时间:2018-05-29 17:07:21

标签: c# entity-framework asp.net-web-api

我正在处理一个WebApi项目,我希望序列化一个List<User>并将其发送给用户。但它只返回[{"$id":"1"}],其中User是由Entity Framework数据库优先模型类生成的实体。

控制器:

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

以下是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; }
 }

我已将这些代码行添加到WebApiConfig.cs文件中。

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

它刚刚解决了双序列化问题。我有我的老问题。 当我向ActionMethod发送请求时,我会收到$id : "1"

我了解到它是因为EntityFramework。因为WebApi无法序列化EntityFramework实体(我认为这是因为我的模型中存在关系)

那我该怎么做才能解决呢? 我不想全部重写它们。

1 个答案:

答案 0 :(得分:0)

试试这个

newTableName = "A_Test_DashAutomation"
try:
    cursor.execute("""
    BEGIN TRANSACTION
    SET QUOTED_IDENTIFIER ON
    SET ARITHABORT ON
    SET NUMERIC_ROUNDABORT OFF
    SET CONCAT_NULL_YIELDS_NULL ON
    SET ANSI_NULLS ON
    SET ANSI_PADDING ON
    SET ANSI_WARNINGS ON
    COMMIT
    BEGIN TRANSACTION """)

    cursor.execute("""
    CREATE TABLE dbo.Tmp_""" + newTableName + """
        (
        SubProjectTempId bigint NULL,
        CIPNumber varchar(16) NOT NULL,
        Label nvarchar(50) NULL,
        Date_Started datetime2(7) NULL,
        Date_Completed datetime2(7) NULL,
        Status nvarchar(25) NULL,
        Shape geography NULL,
        Type varchar(2) NOT NULL,
        ProjectCode varchar(16) NULL,
        ActiveFlag int NULL,
        Category varchar(32) NULL,
        ProjectDescription varchar(64) NULL,
        UserDefined varchar(1024) NULL,
        InactiveReasonDate datetime NULL,
        FYTDBudget money NULL,
        LTDBudget money NULL,
        PeriodExpenses money NULL,
        FYTDExpenses money NULL,
        LTDExpenses money NULL,
        LTDEncumbrances money NULL,
        LTDBalance money NULL,
        FiscalYear int NULL,
        ToPeriod int NULL,
        _LastImported datetime NOT NULL,
        OBJECTID int NOT NULL IDENTITY (1, 1),
        GDB_GEOMATTR_DATA varbinary(MAX) NULL
        )  ON [PRIMARY]
         TEXTIMAGE_ON [PRIMARY]
    """)

    cursor.execute("ALTER TABLE dbo.Tmp_" + newTableName + " SET (LOCK_ESCALATION = TABLE)")

    cursor.execute("SET IDENTITY_INSERT dbo.Tmp_" + newTableName + " ON")

    cursor.execute("""
    IF EXISTS(SELECT * FROM dbo.""" + newTableName + """)
         EXEC('INSERT INTO dbo.Tmp_""" + newTableName + """ (SubProjectTempId, CIPNumber, Label, Date_Started, Date_Completed, Status, Shape, Type, ProjectCode, ActiveFlag, Category, ProjectDescription, UserDefined, InactiveReasonDate, FYTDBudget, LTDBudget, PeriodExpenses, FYTDExpenses, LTDExpenses, LTDEncumbrances, LTDBalance, FiscalYear, ToPeriod, _LastImported, OBJECTID, GDB_GEOMATTR_DATA)
            SELECT SubProjectTempId, CIPNumber, Label, Date_Started, Date_Completed, Status, Shape, Type, ProjectCode, ActiveFlag, Category, ProjectDescription, UserDefined, InactiveReasonDate, FYTDBudget, LTDBudget, PeriodExpenses, FYTDExpenses, LTDExpenses, LTDEncumbrances, LTDBalance, FiscalYear, ToPeriod, _LastImported, OBJECTID, GDB_GEOMATTR_DATA FROM dbo.""" + newTableName + """ WITH (HOLDLOCK TABLOCKX)')
    """)

    cursor.execute("SET IDENTITY_INSERT dbo.Tmp_" + newTableName + " OFF")

    cursor.execute("DROP TABLE dbo." + newTableName)

    cursor.execute("EXECUTE sp_rename N'dbo.Tmp_" + newTableName + "', N'" + newTableName + "', 'OBJECT'")

    cursor.execute("""
    ALTER TABLE dbo.""" + newTableName + """ ADD CONSTRAINT
        R1143_pk PRIMARY KEY CLUSTERED 
        (
        OBJECTID
        ) WITH( PAD_INDEX = OFF, FILLFACTOR = 75, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

    """)

    cursor.execute("""
    CREATE SPATIAL INDEX SIndx ON dbo.""" + newTableName + """(Shape) USING GEOGRAPHY_AUTO_GRID
         WITH( CELLS_PER_OBJECT  = 16, STATISTICS_NORECOMPUTE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
    """)

    cursor.execute("""
    ALTER TABLE dbo.""" + newTableName + """ ADD CONSTRAINT
        g1084_ck CHECK (([Shape].[STSrid]=(4326)))
    """)

    cursor.execute("COMMIT")

    conn.commit()
    print("Object ID is set to Identify column.")

except pymssql.DatabaseError, err:
    print(str(err))

您将在用户中以json和状态代码获得响应。

相关问题