使用带有连接的Linq查询选择实体并包含嵌套属性

时间:2015-05-13 13:47:18

标签: c# linq entity-framework

我正在努力使用EntityFramework和Linq来检索单个模型/实体。

我与会员开展业务,我正在尝试根据BusinessMembers表/实体检索用户的业务。

我有以下实体/模型:

public partial class Business
{
    public Business()
    {
        BusinessMembers = new HashSet<BusinessMember>();
    }

    public int ID { get; set; }

    public int ID_BusinessStatus { get; set; }

    public string Name { get; set; }

    public string Url { get; set; }

    public string Phone { get; set; }

    public virtual BusinessStatus BusinessStatus { get; set; }

    public virtual ICollection<BusinessMember> BusinessMembers { get; set; }
}

 public partial class BusinessStatus
{
    public BusinessStatus()
    {
        Businesses = new HashSet<Business>();
    }

    public int ID { get; set; }

    [Required]
    [StringLength(3)]
    public string Code { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    public virtual ICollection<Business> Businesses { get; set; }
}

然后,我有以下方法返回单个业务实例:

        public Business GetBusinessForUser(string userId)
    {
        using (var db = new MyContext(_connectionString))
        {
            var q =
                   from b in db.Businesses
                   join bm in db.BusinessMembers on b.ID equals bm.ID_Business
                   where bm.UserId == userId
                   select b;

            return q.FirstOrDefault();
        }
    }

我遇到的问题是我想“包含”该单一商业实体的BusinessStatus,但不知道如何执行此操作。

我需要能够做到:

Business businessEntity = _dataServices.GetBusinessForUser(userId);

        if (businessEntity.BusinessStatus.Code == "ACT")
        {
            // Whatever
        }

1 个答案:

答案 0 :(得分:2)

首先,将其添加到使用列表

using System.Data.Entity;

然后,您可以使用.Include()方法在查询中加载其他子项

public Business GetBusinessForUser(string userId)
{
    using (var db = new MyContext(_connectionString))
    {
        var q =
               (from b in db.Businesses
               join bm in db.BusinessMembers on b.ID equals bm.ID_Business
               where bm.UserId == userId
               select b).Include(business => business.BusinessStatus);

        return q.FirstOrDefault();
    }
}

我也会明确避免使用join方法。如果您的模型具有正确的关系(例如外键),您应该能够这样做:

var q = db.Businesses
          .Where(b => b.BusinessMembers.Any(bm => bm.UserId == userId))
          .Include(b => b.BusinessStatus);

return q.FirstOrDefault();

甚至

var q = db.BusinessMembers
          .Where(bm => bm.UserId == userId)
          .Select(bm => bm.Business)
          .Include(b => b.BusinessStatus);