如何 return IEnumerable<T> 为 null

How to return IEnumerable<T> as null

我有下面的 ActivitiesDB.cs,它是一个 DEBentity class。

public class ActivitiesDB
{
public IEnumerable<Activity> Activities { get; set; }
}

public class Activity
{
public Guid ActivityId { get ;set; }
public DateTime ActivityDateTime { get; set; }
public DateTime UpdatedDateTime { get; set; }
public IEnumerable<MetaData> MetaData { get; set; }
}

public class MetaData
{
public string Name { get; set; }
public string Value { get; set; }
}

数据库中的示例数据(我在后端使用 CosmosDb):

"Activities": [
            {
                "ActivityId": "4f436d11-7a61-4e7f-b0fb-0f0d5bb6be76",
                "ActivityDateTime": "2021-04-30T09:35:35.32Z",
                "UpdatedDateTime": "2021-05-03T07:45:21.5115588Z",
                "Metadata": [
                    {
                        "Name": "name",
                        "Value": "value"
                    }
                ]
            },
            {
                "ActivityId": "659e62c5-4408-42b4-8719-b8c577221d22",
                "ActivityDateTime": "2021-04-30T09:35:35.32Z",
                "UpdatedDateTime": "2021-05-03T07:45:21.5115588Z",
                "Metadata": null
            }
        ]

为了显示数据,我在下面 class DisplayActivtiesResponse.cs:

public class DisplayActivtiesResponse
{
public IEnumerable<DisplayActivity> DisplayActivties{ get; set; }
}

public class DisplayActivity
{
public Guid ActivityId { get ;set; }
public DateTime ActivityDateTime { get; set; }
public DateTime UpdatedDateTime { get; set; }
public IEnumerable<MetaData> MetaData { get; set; }
}

public class MetaData
{
public string Name { get; set; }
public string Value { get; set; }
}

下面是从数据库中获取数据的代码:

 public async Task<DisplayActivtiesResponse> DisplayActivityAsync(Guid activityId)
        {
            var feedIterator = this.cosmosReviewRequestContainer.GetItemLinqQueryable<ActivitiesDB>()
                .Where(q => q.Activities.Where(x => x.ActivityId == activityId)
                .ToFeedIterator();
            var requestModel = new ActivitiesDB();
            while (feedIterator.HasMoreResults)
            {
                var items = await feedIterator.ReadNextAsync().ConfigureAwait(false);
                requestModel = items.FirstOrDefault();
            }

            return new DisplayActivtiesResponse
            {
                DisplayActivties = mapper.Map<IEnumerable<DisplayActivity>>(requestModel);
            };
        }

MappingProfile.cs:

 public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            this.CreateMap<Activity, DisplayActivity>().ReverseMap();
        }
    }

现在,当我从数据库中获取数据时,我观察到如果元数据为空,我得到的是空数组 [] 而不是 null。我仍然不知道我到底错过了什么。请帮助我。

初始化时将AllowNullCollections设置为true:

AutoMapper.Mapper.Initialize(cfg =>
{
    cfg.AllowNullCollections = true;
});

或直接在映射器配置中:

new MapperConfiguration(cfg =>
{
    cfg.AllowNullCollections = true;
}