我必须多次从类中选择必需的字段,就像在sql中从Table中选择所需字段一样。 所以我想把我的类和结构化为Projectables。
这是我想要实现的目标。
public class Email
{
public string Subject { get; set; }
public string To { get; set; }
public string Cc { get; set; }
public string Bcc { get; set; }
public string Body { get; set; }
public DateTime ReceivedDate { get; set; }
}
public class EmailProjection
{
// instead of this
//public string Subject { get; set; }
//public DateTime ReceivedDate { get; set; }
// I want to do this
Email.Project(Subject,ReceivedDate);
}
public class EntryPoint
{
static void Main()
{
var emailList = new List<Email>();
/* populate emails here from source*/
// I want to do this
List<EmailProjection> emailProjectionList = emailList.Project(EmailProjection).ToList();
// rather than
List<EmailProjection> emailProjectionList= emailList.Select(email=>new {email.Subject,email.ReceivedDate}).ToList();}
}
有人可以帮我解决这个问题吗?提示?它可以实现吗?
答案 0 :(得分:2)
您可以查看Automapper:https://github.com/AutoMapper/AutoMapper。 它是一个基于命名约定和规则映射DTO的库。 在维基中查看有一个Projection页面,可能是您正在寻找的页面。 只是为了连接你的例子,你最终可以编写如下代码:
Mapper.Map<EMail, EmailProjection>(yourObjects);