如何从数据库创建基于模型的C#列表

时间:2017-10-24 16:36:44

标签: entity-framework relational-database generic-list

我通过Entity Framework创建了模型:

public partial class Order
{
    public Order()
    {
        this.OrderDetails = new HashSet<OrderDetail>();
    }

    public int OrderID { get; set; }
    public string OrderNo { get; set; }
    public System.DateTime OrderDate { get; set; }
    public string Description { get; set; }

    public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}

然后是另一个详细信息表:

 public partial class OrderDetail
{
    public int OrderItemsID { get; set; }
    public int OrderID { get; set; }
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Rate { get; set; }
    public decimal TotalAmount { get; set; }

    public virtual Order Order { get; set; }
}

 To See the Master Detail Data I made MasterDetails model As:

 public class OrderVM
{
    public string OrderNo { get; set; }
    public DateTime OrderDate { get; set; }
    public string Description { get; set; }
    public List<OrderDetail> OrderDetails {get;set;}
}

我试图创建一个返回带有Join查询结果的LIST的方法,但是    我在这里收到#Anonymous类型错误是我的代码:

public static List<OrderVM > mylist()
    {
        List<OrderVM> slist = new List<OrderVM>();

        using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
        {
            var myvalues = from O in dc.Orders
                          join D in dc.OrderDetails
                          on
                          O.OrderID equals D.OrderID
                          select new
                           {
                               O.OrderID,
                               O.OrderDate,
                               D.Quantity,
                               D.Rate
                           };


              foreach(var myorders in myvalues)
              {
                  slist.Add(myorders);
              }

              return slist;


        }
    }

我需要一个帮助,知道如何创建包含数据库字段的通用列表

1 个答案:

答案 0 :(得分:0)

创建新类:

public class OrderDetailsModel
{
    public int OrderId { get; set; }

    public DateTime OrderDate { get; set; }

    public int Quantity { get; set; }

    public decimal Rate { get; set; }
}   

并从您的方法返回此类对象的列表:

    using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
    {
        var myvalues = from O in dc.Orders
                      join D in dc.OrderDetails
                      on
                      O.OrderID equals D.OrderID
                      select new OrderDetailsModel
                      {
                          OrderId = O.OrderID,
                          OrderDate = O.OrderDate,
                          Quantity = D.Quantity,
                          Rate = D.Rate
                      };


          return myvalues.ToList();
    }