.net 按EF Core中的导航属性筛选数据
我有一个小模型:.net 按EF Core中的导航属性筛选数据,.net,entity-framework,entity-framework-core,.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 {
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; }
}
但我不确定我是否做对了。这是正确的方法吗
另外,我想知道这将如何处理
用户中的null社区
几乎是这样,我建议您在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)
行是临时性的,但是我建议您禁用它是的,这是正确的方法。正如一些用户所说,LINQ表达式使用正确的WHERE和JOIN子句正确地转换为SQL。另外,在LINQ to SQL查询中使用FirstOrDefault
时,不必检查null
。是的,这是正确的方法。空导航属性不会影响这一点,因为对导航属性的访问转换为左外部联接,因此临时表(而不是整个对象)中导航属性的所有属性都为空@SuperJMN您的问题解决了吗?请随意接受我的答案以关闭导航属性,因为查询选择在引用的表上是不必要的,并且可能会扰乱您的上下文。这听起来与上下文无关,因为EF Core不支持延迟加载(目前)。此外,当查询转换为SQL并在数据库中执行时,既不需要null
检查也不需要Include
。
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);