【问题标题】:Change serrialization of collection in Odata更改 Odata 中集合的序列化
【发布时间】:2014-10-07 15:22:57
【问题描述】:

我有以下物品:

public class Car 
{
   public virtual int Id {get;set;}
   public virtual IList<Spec> Specs { get; set; }
   public virtual IList<Owner> Owners { get; set; }
}

public class Spec
{
   public virtual int Id { get; set;}
   public virtual string Info { get; set;}
}

 public class Owner: ILast
{
   public virtual int Id { get; set;}
   public virtual string FullName{ get; set;}
   public virtual DateTime DateTime { get; set;}
}

CarOwner 的比例为 1:M,但是当我请求 Car 实体时,我想要的不是数组而是单个实体。

public class BaseController<T> : ApiController where T : IEntity
{
        private readonly IRepository<T, TKey> _repo;

        public BaseReadController(IRepository<T, TKey> repo)
        {
            _repo = repo;
        }

        public IQueryable<T> Get()
        {
          return _repo.Query();
        }
}

如果Query 实现ILast 接口,则Query 返回IQuerable 并具有选择具有最后一个DateTime 属性的实体的谓词。比如我们在Owner表中有如下数据:

所有者表:

id | FullName | DateTime | CarId
1      name1    12.01.13   1
2      name2    15.04.15   1

查询将只返回第二个。

在我将得到的 JSON 结果中(假设 Spec 表也有 2 条记录):

Car = {
  id: 1,
  Specs: {
     [0]: object with spec properties,
     [1]: object with spec properties,   
  },
  Owners: {
     [0]: {
         id: 1,
         FullName: 'name2',
         DateTime: '15.04.5'
      }
  }
}

但是,我想更改序列化,Owners 属性始终包含一条记录。我想得到以下 JSON:

Car = {
      id: 1,
      Specs: {
         [0]: object with spec properties,
         [1]: object with spec properties,   
      },
      Owners: {
         id: 1,
         FullName: 'name2',
         DateTime: '15.04,.5'
      }
    }

我们可以通过接口来判断实体。

附言。我正在使用OData

【问题讨论】:

  • 它只是一个属性的接口DateTime
  • 如果汽车只有一个车主,那为什么还要有车主作为它的财产。保持它只是所有者(而不是列表)
  • @Guanxi:可能因为有很多记录。但用户只能看到一个。它就像历史实体。

标签: c# json.net odata asp.net-web-api asp.net-web-api2


【解决方案1】:

您可以通过编写自定义序列化来实现这一点,但我不建议使用单个对象覆盖数组项表示,因为那样就不是标准。

我建议在您的 Car 对象中创建两个属性,一个所有者和另一个过去的所有者,并且不要使用 JSON 忽略将过去的所有者暴露给用户。

【讨论】:

  • 我正在使用OData 进行数据访问。
猜你喜欢
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
相关资源
最近更新 更多