当URL包含$ select时,自定义序列化程序在oData 4的Web API 2中不起作用

时间:2015-05-25 04:19:03

标签: api select web odata serializer

我通过继承ODataEntityTypeSerializer实现了自定义序列化程序。序列化程序设置" MessageStateName"的值。通过从" MessageState"的值获取BayStateEnum的名称。 除非URL包含" $ select",否则它只能正常工作。我调试了代码并发现它已被执行且entityInstanceContext.EntityInstance具有正确的值,但是SystemInstanceContext.EdmModel,类型为System.Web.OData.Query.Expressions.SelectExpandBinder.SelectSome,仍然有一个空的" MessageStateName& #34;

public class CustomEntitySerializer : ODataEntityTypeSerializer
{
    public CustomEntitySerializer(ODataSerializerProvider serializerProvider)
        : base(serializerProvider)
    {
    }
    public override ODataEntry CreateEntry(SelectExpandNode selectExpandNode, EntityInstanceContext entityInstanceContext)
    {
        if (entityInstanceContext.EntityInstance is SmartLinkInfoModel)
        {
            var smartLinkInfo = entityInstanceContext.EntityInstance as SmartLinkInfoModel;
            if (smartLinkInfo.ModemIMEI != null)
            {
                smartLinkInfo.ModemIMEIString = "0x" + string.Join(string.Empty, smartLinkInfo.ModemIMEI.Select(b => (b - 48).ToString()));
            }
            if (smartLinkInfo.SmartLinkHardwareId != null)
            {
                smartLinkInfo.SmartLinkHardwareIdString = "0x" + string.Join(string.Empty, smartLinkInfo.SmartLinkHardwareId.Select(b => b.ToString()));
            }
            if (smartLinkInfo.XbeeSourceId != null)
            {
                smartLinkInfo.XbeeSourceIdString = "0x" + string.Join(string.Empty, smartLinkInfo.XbeeSourceId.Select(b => b.ToString()));
            }
        }
        else if (entityInstanceContext.EntityInstance is BayMessageModel)
        {
            var bayMessage = entityInstanceContext.EntityInstance as BayMessageModel;
            bayMessage.MessageStateName = Enum.GetName(typeof(BayStateEnum), bayMessage.MessageState);
        }
        return base.CreateEntry(selectExpandNode, entityInstanceContext);
    }
}

1 个答案:

答案 0 :(得分:0)

你的代码改变了entityInstanceContext.EntityInstance是对的,但它不会改变select的结果,你可以看到

object propertyValue = entityInstanceContext.GetPropertyValue(structuralProperty.Name);

ODataEntityTypeSerializer的{​​{1}}方法中,如果CreateStructuralPropertystructuralProperty.Name,则应覆盖此方法,然后使用MessageStateName