如何将EntityField列表添加到SyncEntity列表?

时间:2018-01-11 12:42:28

标签: c#

我想将EntityField列表存储到SyncEntity列表中,但是我收到错误,下面是我的代码片段:

 List<SyncEntity>  syncEntities = new List<SyncEntity>
        {
            new SyncEntity {Name ="Doors_Module2",Id = "1",
                   new EntityField{Name = "Field1"},
                    new EntityField{Name="Field2"}},
            new SyncEntity {Name ="Doors_Module2",Id = "2"},
            new SyncEntity {Name ="Doors_Module2",Id = "3"},
            new SyncEntity {Name ="Doors_Module2",Id = "4"}
        };

存储列表时出错。请帮帮我

1 个答案:

答案 0 :(得分:1)

解决方案很简单。这就是class的定义方式,

public class SyncEntity
{
    public string Name { get; set; }
    public string Id { get; set; }
    public List<EntityField> EntityFields { get; set; }
}

如果您看到EntityFields属性,则需要为其分配EntityField列表。
现在,如果你观察你的代码,你正在创建的第一个SyncEntity对象是这样的,

new SyncEntity
{
    Name = "Doors_Module2",
    Id = "1",
    new EntityField { Name = "Field1" }, //adding object instead of list
    new EntityField { Name = "Field2" }  //adding object instead of list
}

在评论中,您要添加两个单独的对象而不是列表 因此,您必须将这两个对象添加为列表。像,

new SyncEntity
{
    Name = "Doors_Module2",
    Id = "1",
    EntityFields = new List<EntityField> {
        new EntityField { Name = "Field1" },
        new EntityField { Name = "Field2" }
    }
}