如何从ef核心获取所有数据

时间:2019-05-22 04:23:18

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

在EF核心上有两个表(页面,组)都与联结表 GroupPage 有许多关系。想要像基于波纹管一样获取所有基于groupId与联结表相关的数据的页面数据。

enter image description here

2 个答案:

答案 0 :(得分:0)

如果您正确地构建EF关系,则您不应该拥有GroupPage实体。

有关如何正确构建EF EDM的信息,请参见Entity Framework Database First many-to-many

一旦正确映射了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;
}

答案 1 :(得分:0)

以下语法是自描述的。这是实体结构和Page 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;

}