如何根据其他表中的多个值过滤 Linq

问题描述 投票:0回答:1

我有一个简单的 linq 语句,但我现在需要包含来自其他实体的数据。 我想接收元实体,其中 ViewId 等于 View 中的 Id,并且 View.SiteId = site.Id。

我得到了什么:

Metas = await siteExp.MetaEntriesAsync(m => m.SiteId == site.Id || m.ViewId == ?????)

在 SQL 中我会做类似的事情:

SELECT m.* FROM SiteMeta m, SiteView sv WHERE sv.SiteId = 4 AND sv.Id = m.ViewId

两个实体:

public class Meta : DbAssets, IMeta
{
    public int? SiteId { get; set; }
    public int? ViewId { get; set; }
    public int? CultureId { get; set; }
    public virtual Culture Culture { get; set; }
    public string Content { get; set; }
    public string Name { get; set; }
    public bool OverrideTitle { get; set; } = false;
    public bool ReplaceExisting { get; set; } = false;
}

public class View : DbRef, IView
{
    public int SiteId { get; set; }

    [Required]
    public string Name { get; set; }
    public virtual IEnumerable<Meta> Metas { get; set; } = new HashSet<Meta>();
    public virtual IEnumerable<ViewInfo> Infos { get; set; } = new HashSet<ViewInfo>();
    public int? CultureId { get; set; }
    public string? Title { get; set; }
    public bool ReplaceTitle { get; set; } = false;
    public virtual Culture? Culture { get; set; }
}

谢谢!

c# sql-server database linq asp.net-core
1个回答
0
投票
  1. 您需要一个从 Meta 到 View 的导航属性。

public class Meta : DbAssets, IMeta
{
    public int? SiteId { get; set; }

    public int? ViewId { get; set; }
    public virtual View View { get; set; } // add this

    public int? CultureId { get; set; }
    public virtual Culture Culture { get; set; }
    public string Content { get; set; }
    public string Name { get; set; }
    public bool OverrideTitle { get; set; } = false;
    public bool ReplaceExisting { get; set; } = false;
}
  1. 然后在查询中,您可以访问该导航属性进行过滤。
Metas = await siteExp.MetaEntriesAsync(m => m.SiteId == site.Id || m.View?.SiteId == site.Id))

or

Metas = await siteExp.MetaEntriesAsync(m => m.SiteId == site.Id || (m.View != null && m.View.SiteId == site.Id))
© www.soinside.com 2019 - 2024. All rights reserved.