按EF Core中的导航属性过滤数据

时间:2017-12-04 13:53:36

标签: .net entity-framework entity-framework-core

我有这个小型号:

class User
{
    public int Id { get; set; }
    public Community { get; set; }
}

class Community
{
    public int Id { get; set; }
    public Country { get; set; }
}

class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
}

DbContext 是这样的:

public class SmallDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
}

我想创建一个查询来检索给定Users的{​​{1}}

我的赌注是:

Country

但我不确定我是否正确行事。这是正确的方法吗?

另外,我想知道这将如何处理int countryId = 2: var usersOfAGivenCountry = dbContext.Users .Where(community => community.Country.Id == countryId); 中的空Community

2 个答案:

答案 0 :(得分:0)

几乎就是这样,我建议你在null案例中添加条件,你必须在模型中声明外键,如:

class User
{
    public int Id { get; set; }
    public int CommunityId { get; set; }
    [ForeignKey("CommunityId")] // facultative because it respects naming convention Modelname + "Id"
    public Community { get; set; }
}

class Community
{
    public int Id { get; set; }
    public int CountryId { get;set; }
    [ForeignKey("CountryId")] // facultative because it respects naming convention Modelname + "Id"
    public Country { get; set; }
}
var usersOfAGivenCountry = dbContext.Users
      .Include(p => p.Community)
      .Where(community => community != null
             && community.CountryId == countryId);

如果您启用了延迟加载模式,则行.Include(p => p.Community)是兼容性的,但我建议您禁用它

答案 1 :(得分:0)

是的,这是正确的方法。正如某些用户所说,LINQ表达式使用正确的WHERE和JOIN子句可以正确地转换为SQL。另外,在LINQ to SQL查询中使用null时,也不必检查FirstOrDefault