在Include存储库方法中调用多个Lambda表达式

本文关键字:Lambda 表达式 调用 Include 存储 方法 | 更新日期: 2023-09-27 18:03:49

我找到了这个通用存储库,但我确实找到了一种使用它的方法:

    public T FindSingle(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes)
    {
        var set = FindIncluding(includes);
        return (predicate == null) ? set.FirstOrDefault() : set.FirstOrDefault(predicate);
    }

我如何调用它来包含像这样的几个相关实体?:

        Message messageParentDomain = _messageRepository.FindSingle(m => m.Id == messageDto.MessageParent_Id, includes: i => i.MemberFrom, i => i.MemberTo);  
消息类:

public class Message
{
    // Primary properties
    public int Id { get; set; }
    public string NameFrom { get; set; }
    public string EmailFrom { get; set; }
    public string TelephoneFrom { get; set; }
    public string Title { get; set; }
    public string MessageText { get; set; }
    public bool? Approved { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateRead { get; set; }
    // Navigation properties
    public Member MemberFrom { get; set; }
    public Member MemberTo { get; set; }
    public MessageType MessageType { get; set; }
    public Message MessageParent { get; set; }
    public Ad Ad { get; set; }
    public Ask Ask { get; set; }
}

谢谢。

在Include存储库方法中调用多个Lambda表达式

下面是编译方法的一个版本:

public T FindSingle<T>(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes)
{
    var set = FindIncluding(includes);
    return (predicate == null) ? set.FirstOrDefault() : set.FirstOrDefault(predicate);
}

我假设T被称为Message(你不能通过T)给我们FindSingle<Message>Expression<Func<Message, object>>。你需要用你真正使用的对象来替换T。试试这段代码…

Message messageParentDomain = 
    _messageRepository.FindSingle<Message>(
        m => m.Id == messageDto.MessageParent_Id, 
        includes: new Expression<Func<Message, object>>[] {
            i => i.MemberFrom,
            i => i.MemberTo
        });