請原諒我,如果這已被問及。我只是剛開始使用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
});
}
UPDATE:
這是我需要做的:
return m => (new CustomerSummary()
{
ID = m.ID,
CustomerName = m.CustomerName,
LastSalesContact = new Person()
{
PersonId = m.LatestPerson.PersonId,
PersonName = m.LatestPerson.PersonName,
Company = new Company()
{
CompanyId = m.LatestPerson.Company.CompanyId,
etc
}
}
});
但我會重新使用Person()
創建約10-15個不同的類,所以我不想完全相同的代碼重複X次的次數。我可能也想爲Company
做同樣的事情。
我應該澄清,我使用EntityFramework,所以這可能會拋出一些不支持的方法錯誤。 – GenericTypeTea 2010-08-03 15:01:46
@GenericTypeTea - 爲什麼?我一直使用automapper和EF。你能發表一個你將如何使用的例子此方法? – Necros 2010-08-03 18:12:43
不起作用:LINQ to Entities無法識別方法'Domain.Models.CustomerSummary Map [TblCustomer,CustomerSummary](Dal.Model.TblCustomer)'方法,並且此方法無法轉換爲as撕裂表情。我試圖在EF Select中使用它。 – GenericTypeTea 2010-08-03 19:27:09