C# Web API JSON反序列化在setter之前调用getter

C# Web API JSON反序列化在setter之前调用getter,c#,json,asp.net-web-api,deserialization,lazy-loading,C#,Json,Asp.net Web Api,Deserialization,Lazy Loading,我有一门课叫菜单。菜单有一个私有列表变量_节和一个公共列表变量节。我使用以下模式进行延迟加载。这还允许我在序列化时检索子项 public class Menu { public int Id; private List<MenuSection> _Sections = null; public List<MenuSection> Sections { get { return _Se

我有一门课叫菜单。菜单有一个私有列表变量_节和一个公共列表变量节。我使用以下模式进行延迟加载。这还允许我在序列化时检索子项

public class Menu 
{
    public int Id;
    private List<MenuSection> _Sections = null;
    public List<MenuSection> Sections
    {
        get
        {
            return _Sections ?? (_Sections = MenuSection.GetListByMenu(Id)); //database call
        }
        set
        {
            _Sections = value;
        }
    }
}
公共类菜单
{
公共int Id;
私有列表_Sections=null;
公开名单部分
{
收到
{
返回_Sections???(_Sections=menusecoction.GetListByMenu(Id));//数据库调用
}
设置
{
_截面=值;
}
}
}
然后修改集合客户端,并将其作为JSON发送回API

我的问题是节的getter在setter之前被调用。这意味着从数据库中重新填充集合,然后添加我现在更新的部分

我已经创建了以下工作,但它很难看,我不想记住在我想加载的任何地方都这样做

public class Menu 
{
    public int Id;
    private bool deserialized = false;

    [OnDeserializing()]
    internal void OnDeserializingMethod(StreamingContext context)
    {
        DeserializerCalled = true;
    }

    private List<MenuSection> _Sections = null;
    public List<MenuSection> Sections
    {
        get
        {
            return _Sections ?? (_Sections = DeserializerCalled ? new List<>() : MenuSection.GetListByMenu(Id));
        }
        set
        {
            _Sections = value;
        }
    }
}
公共类菜单
{
公共int Id;
私有bool反序列化=false;
[正在序列化()]
内部void OnDeserializingMethod(StreamingContext上下文)
{
反序列化调用=true;
}
私有列表_Sections=null;
公开名单部分
{
收到
{
返回_Sections??(_Sections=DeserializerCalled?new List():menusAction.GetListByMenu(Id));
}
设置
{
_截面=值;
}
}
}

我是否缺少一些属性或全局JSON设置来解决这个问题?

问题在于getter实际上是在设置变量,而您只是在与框架抗争。get块应该只返回_Sections集合的值。为什么不考虑使用C#4中引入的惰性构造

private Lazy _someVariable=new Lazy(()=>menusecoction.GetListByMenu(id));
公共字符串SomeVariable=>\u SomeVariable

作为补充说明,我建议在这里遵循正确的命名约定,让私有成员使用驼峰大小写:_部分。

惰性值工厂不允许我传入非静态idI,也更新了答案。只需使用lambda表达式@我试过了。此处无法使用匿名函数。我能够让它以这种方式在构造函数中赋值,但是到那时已经太晚了。