加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

linq – 如何在另一个表达式中创建表达式?

发布时间:2020-12-16 06:54:30 所属栏目:百科 来源:网络整理
导读:如果已经提出这个问题,请原谅我.我刚刚开始使用LINQ.我有以下表达式: public static ExpressionFuncTblCustomer,CustomerSummary SelectToSummary(){ return m = (new CustomerSummary() { ID = m.ID,CustomerName = m.CustomerName,LastSalesContact = //
如果已经提出这个问题,请原谅我.我刚刚开始使用LINQ.我有以下表达式:

public static Expression<Func<TblCustomer,CustomerSummary>> SelectToSummary()
{
    return m => (new CustomerSummary()
    {
        ID = m.ID,CustomerName = m.CustomerName,LastSalesContact = // This is a Person entity,no idea how to create it
    });
}

我希望能够填充LastSalesContact,它是一个Person实体.

我希望填充的详细信息来自m.LatestPerson,因此如何将m.LatestPerson中的字段映射到LastSalesContact.我希望映射可以重用,即我不想这样做:

LastSalesContact = new Person()
{
   // Etc
}

我可以使用静态表达式,例如:

public static Expression<Func<TblUser,User>> SelectToUser()
{
    return x => (new User()
    {
        // Populate
    });
 }

更新:

这就是我需要做的事情:

return m => (new CustomerSummary()
{
    ID = m.ID,LastSalesContact = new Person()
    {
       PersonId = m.LatestPerson.PersonId,PersonName = m.LatestPerson.PersonName,Company = new Company()
       {
           CompanyId = m.LatestPerson.Company.CompanyId,etc
       }
    }
});

但是我将在大约10-15个不同的类中重新使用Person()创建,因此我不希望完全相同的代码重复X次.我可能也想为公司做同样的事情.

解决方法

难道你不能只使用 automapper吗?

public static Expression<Func<TblCustomer,CustomerSummary>> SelectToSummary()
{
    return m => Mapper.Map<TblCustomer,CustommerSummary>(m);
}

你必须做一些自举,但它是非常可重用的.

更新:

我可能没有得到什么,但这个功能的目的是什么?如果您只想将Tbl对象的一个??或集合映射到其他对象,为什么要使用表达式?

你可以这样:

var customers = _customerRepository.GetAll(); // returns IEnumerable<TblCustomer>
var summaries = Mapper.Map<IEnumerable<TblCustomer>,IEnumerable<CustomerSummary>>(customers);

还是我错过了什么?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读