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

时间:2013-03-14 15:17:17

标签: c# asp.net-mvc linq entity-framework

我找到了这个Generic Repository,但我找到了一种方法来使用它:

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

感谢。

1 个答案:

答案 0 :(得分:0)

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

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