我正在研究一个投影实用程序并且有一个最后(更多?)障碍来清除......
以下是该方案:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int? AddressID { get; set; }
public Address Address { get; set; }
public string Otherproperty1 { get; set; }
public string Otherproperty2 { get; set; }
public string Otherproperty3 { get; set; }
public string Otherproperty4 { get; set; }
}
public class PersonSummary
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int? AddressID { get; set; }
public AddressSummary Address { get; set; }
}
public class Address
{
public int AddressID { get; set; }
public string HouseNumber { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Otherproperty1 { get; set; }
public string Otherproperty2 { get; set; }
public string Otherproperty3 { get; set; }
public string Otherproperty4 { get; set; }
}
public class AddressSummary
{
public int AddressID { get; set; }
public string HouseNumber { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
}
我成功地使用了这样的工具:
ProjectionUtility.Project<Person,PersonSummary>();
将返回此Expression Lambda:
p => new PersonSummary(){
FirstName = p.FirstName,
LastName = p.LastName,
AddressID = p.AddressID,
Address = p.AddressID.HasValue
? new AddressSummary(){ AddressID = p.Address.AddressID, HouseNumber = p.Address.HouseNumber, etc... }
: new AddressSummary(){}
}
如果AddressID.HasValue为false,我的目标是能够设置Address = null:
p => new PersonSummary(){
FirstName = p.FirstName,
LastName = p.LastName,
AddressID = p.AddressID,
Address = p.AddressID.HasValue
? new AddressSummary(){ AddressID = p.Address.AddressID, HouseNumber = p.Address.HouseNumber, etc... }
: null
}
这很容易“手动”完成,但是当我尝试使用表达式以编程方式创建这个lambda时,我被卡住了......
我目前正在使用基本上分解为此的内容(我知道语法不对,但我这样做是为了试图展示我正在做的事情):
Expression.Condition(
p.AddressID.HasValue,
new AddressSummary(){},
new AddressSummary(){});
如果我试试这个:
Expression.Condition(
p.AddressID.HasValue,
new AddressSummary(){},
null);
我不能,因为iftrue和iffalse必须是同一类型(AddressSummary)所以我暂时停留为iffalse参数创建一个新的AddressSummary。
有什么想法吗?
谢谢!
答案 0 :(得分:1)
您需要将null转换为正确的类型。在这种情况下:
Expression.Condition(
p.AddressID.HasValue,
new AddressSummary(){},
(AddressSummary)null);
null可以是任何(引用)类型,但默认情况下它的类型为System.Object。如果你想要它是另一种类型,你必须告诉它。