如何通过通用存储库快速加载来获取子实体

时间:2019-05-28 09:57:26

标签: c# entity-framework repository-pattern

我有一个由高级开发人员提供的通用存储库模式。这里我有一个返回List<T>

的方法
     /// <summary>
    /// Get all entities from db
    /// </summary>
    /// <param name="filter"></param>
    /// <param name="orderBy"></param>
    /// <param name="includes"></param>
    /// <returns></returns>
    public virtual List<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includes)
    {
        IQueryable<T> query = dbSet;

        foreach (Expression<Func<T, object>> include in includes)
            query = query.Include(include);

        if (filter != null)
            query = query.Where(filter);

        if (orderBy != null)
            query = orderBy(query);

        return query.ToList();
    }

我有这些实体:

/// <summary>
/// POCO Ticket Object
/// </summary>
public partial class Ticket : Core
{
    public int Status { get; set; }
}
/// <summary>
/// Ticket Virtual Properties
/// </summary>
public partial class Ticket
{
    public virtual ICollection<Conversation> Conversations { get; set; }
}

/// <summary>
/// POCO Conversation Object
/// </summary>
public partial class Conversation : Core
{
    public string Title { get; set; }
    public string Text { get; set; }
    public string UserId { get; set; }
    public string FullName { get; set; }

    //Foreign Keys
    public Guid TicketId { get; set; }
}
/// <summary>
/// Conversation Virtual Properties
/// </summary>
public partial class Conversation
{
    public virtual Ticket Ticket { get; set; }
    public virtual ICollection<Accessory> Accessories { get; set; }
}

/// <summary>
/// POCO Accessory Object
/// </summary>
public partial class Accessory : Core
{
    public string Address { get; set; }
    public string Name { get; set; }
    public string Extension { get; set; }

    //Foreign Keys
    public Guid ConversationId { get; set; }
}
/// <summary>
/// Accessory Virtual Properties
/// </summary>
public partial class Accessory
{
    public virtual Conversation Conversation { get; set; }
}

我想用这种方法实现的是获取所有票证和所有相关的对话以及给定对话可能具有的任何附件。

但是,当我尝试这样做时:

    ret = _unitOfWork.TicketRepository.Get(includes: x => x.Conversations);

这仅返回所有票证和相关的对话。也尝试过此操作,但它不了解此层中的include方法。

    ret = _unitOfWork.TicketRepository.Get(includes: x => x.Conversations.Include(row => row.Accessories));

我想知道如何实现这一目标?我需要有机会使用泛型get方法吗?还是我错误地将值传递给方法?

0 个答案:

没有答案