Linq SelectMany With Null Child

时间:2014-01-04 05:14:08

标签: c# linq nhibernate

MenuSetup和AccessRules具有一对多的关系,如下所述。

public class MenuSetup
{
    public virtual int MenuId { get; set; }
    public virtual string DisplayText { get; set; }
    public virtual int MenuOrder { get; set; }
    public virtual bool MenuStatus { get; set; }
    public virtual bool HasKids { get; set; }

    public virtual IList<MenuAccessRules> AccessRules { get; set; }
}

    public class MenuAccessRules
{
    public virtual int Id { get; set; }
    public virtual Boolean CanCreate { get; set; }
    public virtual Boolean CanUpdate { get; set; }
    public virtual Boolean CanDelete { get; set; }
    public virtual FamsRoles Roles { get; set; }
    public virtual MenuSetup Menu { get; set; }
}

我想在视图模型

中投影下面的查询结果
var result = session.QueryOver<MenuSetup>()
            .Where(p => p.MenuId == id)
            .List();
var vs = result.SelectMany(x => x.AccessRules, (a, b) => new MenuDetailsViewModel
        {
            MenuId = a.MenuId,
            DisplayText = a.DisplayText,
            MenuOrder = a.MenuOrder,
            HasKids = a.HasKids,
            MenuStatus = a.MenuStatus,
            AccessRuleLists = a.AccessRules.
                Select(c => new AccessRulesList { 
                    Id = b.Id, 
                    MenuId = b.Menu.MenuId, 
                    RoleId = b.Roles.RoleId,
                    CanCreate = b.CanCreate, 
                    CanUpdate = b.CanUpdate, 
                    CanDelete = b.CanDelete }).ToList()
        }).SingleOrDefault();

当AccessRules有数据时,vs返回MenuDetailsViewModel,但当AccessRules为Empty时返回null。

请如何制作我的selectMany以返回MenuDetailsViewModel而不管AccessRules数据。

提前感谢您的帮助

2 个答案:

答案 0 :(得分:0)

检查以下代码可能有帮助

 var vs = result.SkipWhile(a=> a.AccessRules==null).SelectMany(x => x.AccessRules, (a, b) => new MenuDetailsViewModel
    {
        MenuId = a.MenuId,
        DisplayText = a.DisplayText,
        MenuOrder = a.MenuOrder,
        HasKids = a.HasKids,
        MenuStatus = a.MenuStatus,
        AccessRuleLists = a.AccessRules.
            Select(c => new AccessRulesList { 
                Id = b.Id, 
                MenuId = b.Menu.MenuId, 
                RoleId = b.Roles.RoleId,
                CanCreate = b.CanCreate, 
                CanUpdate = b.CanUpdate, 
                CanDelete = b.CanDelete }).ToList()
    }).SingleOrDefault();

答案 1 :(得分:0)

会是这样的:

var vs = result.Select(x => new MenuDetailsViewModel
{
    MenuId = x.MenuId,
    DisplayText = x.DisplayText,
    MenuOrder = x.MenuOrder,
    HasKids = x.HasKids,
    MenuStatus = x.MenuStatus,
    AccessRuleLists = x.AccessRules == null ? null : x.AccessRules.
        Select(c => new AccessRulesList
        {
            Id = c.Id,
            MenuId = c.Menu.MenuId,
            RoleId = c.Roles.RoleId,
            CanCreate = c.CanCreate,
            CanUpdate = c.CanUpdate,
            CanDelete = c.CanDelete
        }).ToList()
}).SingleOrDefault();