简体   繁体   English

需要使用扩展方法/查询语法在LINQ中进行左外部联接

[英]Need Left Outer Join in LINQ using Extension Method /Query Syntax

i have a schema with the following structure; 我有一个具有以下结构的模式;
在此处输入图片说明

Basically, a menu can have nested childs. 基本上,菜单可以具有嵌套子级。 And the other tables just holds ItemType , and the Id of the that item ie ItemTypeId (these are referenced dynamically when user choos options at backend). 而其他表仅包含ItemType以及该项目的ID(即ItemTypeId (当用户在后端选择选项时会动态引用它们)。 Now, for menus to be displayed, i have used Inner Join (i want here to use Left Outer Join ) here; 现在,对于要显示的菜单,我在这里使用了内部联接 (我想在这里使用左外部联接 );

public IQueryable<Menu> GetMenuWithAsset()
{
    return DbContext.Set<Menu>()
                    .Join(DbContext.Set<Asset>(), m => m.MenuId, a => a.MenuId, (m, a) => m);
}

and in my base controller, i'm fetching it like this; 在我的基本控制器中,我像这样获取它;

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var menus = Uow.Menus.GetMenuWithAsset()

        .Select(m => new ParentMenuViewModel()
        {
            MenuId = m.MenuId,
            Name = m.Name,
            ParentId = m.ParentId
        })
        .ToList<ParentMenuViewModel>();
    ViewBag.Menus = CreateVM(0, menus);
    base.OnActionExecuting(filterContext);
}

public IEnumerable<ParentMenuViewModel> CreateVM(int parentid, List<ParentMenuViewModel> list)
{
    var newList = list.Where(m=> m.ParentId==parentid)
        .Select(m=> new ParentMenuViewModel()
        {
            MenuId = m.MenuId,
            Name = m.Name,
            ParentId = m.ParentId,
            ChildMenus = CreateVM(m.MenuId, list)
        });
    return newList;
}

And this code works correctly as expected. 并且此代码可以按预期正常工作。 However, here is what i want; 但是,这就是我想要的;
1) I want to display all the menus(including child menus) whetere we have data or not in Asset table ( i gess left outer join). 1)我想显示Asset表中是否有数据的所有菜单(包括子菜单)(我想离开外部联接)。
2) I want to achieve this using strongly typed viewmodel which will hold the following properties from both of the tables 2)我想使用强类型的视图模型来实现这一点,该模型将包含两个表的以下属性
i) MenuId ii) Name iii)ParentId iv) ChildMenus v)MenuItemType vi) MenuItemTypeId i)MenuId ii)名称iii)ParentId iv)ChildMenus v)MenuItemType vi)MenuItemTypeId
I'm trying to solve this from 4 days. 我正在尝试从4天开始解决这个问题。 Any help regard to this is apreciatable; 任何对此的帮助都是可以的;

Try this query: 试试这个查询:

DbContext.Set<Menu>()
         .GroupJoin(DbContext.Set<Asset>(), m => m.MenuId, a => a.MenuId, (m, as) => new { m, as = as.DefaultIfEmpty() });

It will return anonymus class with property m of type Menu and property as that contains IQueriable of Assets. 它将返回匿名类,其属性类型为Menu,属性为包含资产的IQueriable。 I hope this is what you want. 我希望这就是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM