选择具有LINQ查询的类的所有记录

时间:2013-08-31 07:00:47

标签: c# linq ado.net-entity-data-model

我正在尝试从linq查询中获取一些记录

dataentities db = new dataentities();
db.Tabel1.Select(x=> new lcclsAccDueList {LedgerName ,LedgerId,Amount ,AmountInString ,Expr2,Name ,StopID ,VIP  }).ToList();

我做了这个课

 public class lcclsAccDueList
    {
        public string LedgerName { get; set; }
        public decimal LedgerId { get; set; }
        public Nullable<decimal> Amount { get; set; }
        public string AmountInString { get; set; }
        public Nullable<int> Expr2 { get; set; }
        public string Name { get; set; }
        public Nullable<decimal> StopID { get; set; }
        public Nullable<bool> VIP { get; set; }
    }

是否有其他方法可以选择所有记录,例如

dataentities db = new dataentities();
db.Tabel1.Select(x=> new lcclsAccDueList { * }).ToList();
// * indicates select all records 

1 个答案:

答案 0 :(得分:3)

您可以创建lcclsAccDueList类构造函数,该构造函数接受source并映射所有属性:

public class lcclsAccDueList
{
    public lcclsAccDueList() {}
    public lcclsAccDueList(tableItem source)
    {
        LedgerName = source.LedgerName;
        LedgerId = source.LedgerId;
        // (...)
    }

    public string LedgerName { get; set; }
    public decimal LedgerId { get; set; }
    // (...)
}

然后在您的查询中使用它:

dataentities db = new dataentities();
db.Tabel1.Select(x => new lcclsAccDueList(x)).ToList();

或者您可以使用自动映射库,例如automapper

创建地图:

Mapper.CreateMap<tableItem, lcclsAccDueList>();

然后在你的查询中使用它:

dataentities db = new dataentities();
db.Tabel1.Select(x => Mapper.Map<lcclsAccDueList>(x);).ToList();