繁体   English   中英

使用Entity Framework减少数据库调用

[英]Reduce database calls with Entity Framework

是否有可能在1个语句中写这个(只进行1分贝调用?)并且仍能区分“成员不存在”和“成员确实存在但没有狗”。

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;
}

如果每只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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM