【问题标题】:Reduce database calls with Entity Framework使用 Entity Framework 减少数据库调用
【发布时间】:2015-09-25 07:20:18
【问题描述】:

是否可以在 1 条语句中编写此内容(仅进行 1 次 db 调用?)并且仍然能够区分“该成员不存在”和“该成员确实存在但没有狗”。

public IEnumerable<Dog> GetDogsOfMember(int id)
{
    if (dbContext.Members.Any(i => i.ID == id))
    {
        return dbContext.Dogs.Where(i => i.Member.ID == id);
    }

    return null;
}

【问题讨论】:

  • 默认情况下,如果你的 .Where 没有结果,它会导致你“没有错误”,搜索后返回 null。因此,即使不检查,您也可以将其编码为 public IEnumerable GetDogsOfMember(int id) { return dbContext.Dogs.Where(i => i.Member.ID == id); }
  • 你使用缓存来限制数据库调用
  • 没错,但我希望能够区分“如果该成员不存在”或“如果该成员没有狗”。我想我可以使用它。

标签: c# entity-framework database-performance


【解决方案1】:

如果每个Dog 已经包含对Member 的引用,您可以公开关系的另一端(如果您还没有):

public class Member
{
    public int ID { get; set; }
    // ...
    public virtual ICollection<Dog> Dogs { get; set; }
}

然后您可以使用Include() 发出一个有效的查询:

public IEnumerable<Dog> GetDogsOfMember(int id)
{
    var memberWithDogs = dbContext.Members
                                  .Include(i => i.Dogs)
                                  .SingleOrDefault(i => i.ID == id);

    if (memberWithDogs != null)
        return memberWithDogs.Dogs;

    return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 2014-09-03
    • 1970-01-01
    • 2011-07-05
    • 2021-04-21
    相关资源
    最近更新 更多