我有以下代码:
public abstract class AdvancedDeductionAbstractVM
{
public int ID { get; set; }
[Display(Name = "Driver Name")]
public string DriverName { get; set; }
public string Description { get; set; }
[Display(Name = "Date")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime DateTime { get; set; }
[Display(Name = "Amount")]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal Amount { get; set; }
}
public class AdvancedDeductionElementVM : AdvancedDeductionAbstractVM
{
}
public class AdvancesDeductionDetailVM : AdvancedDeductionAbstractVM
{
}
public class AdvancesDeductionDeleteVM : AdvancedDeductionAbstractVM
{
}
表达式:
private Expression<Func<AdvancesDeduction, T>> GetAdvancesDeductionAbstractExpression<T>() where T : AdvancedDeductionAbstractVM, new()
{
Expression<Func<AdvancesDeduction, T>> projection = i =>
new T()
{
ID = i.ID,
Amount = i.Amount,
DateTime = i.DateTime,
Description = i.Description,
DriverName = i.Driver.Name
};
return projection;
}
并使用它:
AdvancesDeductionDetailVM model = (from i in db.AdvancesDeductions
where i.ID == id.Value
select i)
.Select(GetAdvancesDeductionAbstractExpression<AdvancesDeductionDetailVM>()).FirstOrDefault();
AdvancesDeductionDeleteVM model = (from i in db.AdvancesDeductions
where i.ID == id.Value
select i).Select(GetAdvancesDeductionAbstractExpression<AdvancesDeductionDeleteVM>()).FirstOrDefault();
它有效,但我想将它添加到Linq实体,而不是使用Lambda表达式。有什么方法可以使用它吗?
答案 0 :(得分:2)
您可能想查看NeinLinq 之后你可以做到
[InjectLambda]
public static bool To<T>(this AdvancedDeductionAbstractVM value) where T : AdvancedDeductionAbstractVM, new()
{
throw new NotImplementedException();
}
public static Expression<Func<AdvancedDeductionAbstractVM,T>> To<T>() where T : AdvancedDeductionAbstractVM, new()
{
return i =>
new T()
{
ID = i.ID,
Amount = i.Amount,
DateTime = i.DateTime,
Description = i.Description,
DriverName = i.Driver.Name
};
}
并像
一样使用它AdvancesDeductionDetailVM model = (from i in db.AdvancesDeductions.ToInjectable()
where i.ID == id.Value
select i.To<AdvancesDeductionDetailVM>()).FirstOrDefault();