【问题标题】:How to get all data from ef core many to many如何从ef core多对多获取所有数据
【发布时间】:2019-05-24 13:07:23
【问题描述】:

在 EF 核心上有两个表(Page,Group)都与联结表 GroupPage 有多对多的关系。想要根据 groupId 获取所有带有联结表相关数据的页面数据,如下所示。

【问题讨论】:

标签: database entity-framework entity-framework-core aspnetboilerplate


【解决方案1】:

如果你正确地构建了你的 EF 关系,你就不应该有 GroupPage 实体。

请参阅Entity Framework Database First many-to-many,了解如何正确构建您的 EF EDM。

正确映射 EDM 后,您应该拥有类

public class Page
{
    public int Id { get; set; }
    public ICollection<Group> Groups { get; set; }
    ...
}

public class Group
{
    public int Id { get; set; }
    public ICollection<Page> Pages { get; set; }
    ...
}

那么你只需要执行以下操作

public IQueryable<Page> GetPages(int groupId)
{
    return from group in _context.Groups
           where group.Id == groupId
           from page in group.Pages
           select page;
}

【讨论】:

    【解决方案2】:

    以下语法是自描述的。这是实体结构和页面 Dto。

    public class Page
    {
        public int Id { get; set; }
        public ICollection<Group> Groups { get; set; }
        ...
    }
    
    public class Group
    {
        public int Id { get; set; }
        public ICollection<Page> Pages { get; set; }
        ...
    }
    
    
    public class PageGroup
    {
        public int PageId { get; set; }
        public Page Page { get; set; }
        public int GroupId { get; set; }
        public Group Group { get; set; }   
    }
    
    
    public class PagesDto 
    {
        public string Name { get; set; }
        public int GroupId { get; set; }
        public int PageId { get; set; }
        public string Description { get; set; }
        public string Tab { get; set; }
        public string Module { get; set; }
        public bool? IsActive { get; set; }
        public bool? IsDefault { get; set; }
    
        public PagesDto()
        {
            IsActive = false;
            IsDefault = false;
        }
    }
    

    以下功能帮助我们获取群组相关页面信息。

    public async Task<List<PagesDto>> GetAllPagesByGroupId(int selectedGroupId)
    {
        //get all pages
        var pages = await _pagesRepository.GetAll().Select(p => new PagesDto {
            PageId = p.Id,
            Name = p.Name,
            GroupId = 0
    
        }).ToListAsync();
    
        //get group ralated pages
        var selectedGroupPageIds = _groupPagesRepository
            .GetAll()
            .Where(p => p.GroupId == selectedGroupId)
            .Select(p => p.PageId);
    
        //update page information base on group related pages info.
        foreach (var item in pages.Where(p=>selectedGroupPageIds.Contains(p.PageId)))
        {
            item.GroupId = selectedGroupId;                
        }
    
        return pages;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2020-11-19
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多