使用Entity Framework从数据库中检索数据

时间:2014-10-20 07:46:00

标签: c# wpf entity-framework

我是Entity Framework的初学者。我正在构建一个WPF应用程序。以下是我的模型类:

[Table("Vehicle")]
    public class Vehicle
    {
        [Key]
        public int VehicleId { get; set; }
        [Column("LicencePlateNumber", TypeName = "ntext")]
        [MaxLength(100)]
        public string LicencePlateNumber { get; set; }
        [Column("LicencePlateState", TypeName = "ntext")]
        [MaxLength(100)]
        public string LicencePlateState { get; set; }
        [Column("Make", TypeName = "ntext")]
        [MaxLength(100)]
        public string Make { get; set; }
        [Column("Other", TypeName = "ntext")]
        [MaxLength(100)]
        public string Other { get; set; }
        [Column("Model", TypeName = "ntext")]
        [MaxLength(100)]
        public string Model { get; set; }
        [Column("Style", TypeName = "ntext")]
        [MaxLength(100)]
        public string Style { get; set; }
        [Column("Color", TypeName = "ntext")]
        [MaxLength(100)]
        public string Color { get; set; }
        [Column("PurchaseYear", TypeName = "int")]
        public int PurchaseYear { get; set; }
        [Column("InsurnaceCompanyName", TypeName = "ntext")]
        [MaxLength(100)]
        public string InsurnaceCompanyName { get; set; }
        [Column("InsurnaceCompanyNumber", TypeName = "ntext")]
        [MaxLength(100)]
        public string InsurnaceCompanyNumber { get; set; }
    }

我正在尝试从datagrid中的此表中检索数据。

 using (var context = new TransportContext())
 {                
       var vehicleList = from v in context.Vehicles
                         select new
                         {
                              Number = v.LicencePlateNumber,
                              Make = v.Make,
                              Model = v.Model,
                              Year = v.PurchaseYear
                         };
                    DG_Details.ItemsSource = vehicleList;
                    DG_Details.Items.Refresh();
   }

但我得到XAMLParseException。另一方面,如果我尝试这个,那么它的工作原理:

 using (var context = new TransportContext())
 {              
       var projectionQuery = from v in context.Vehicles
                                  select v;
            var vehicleList = projectionQuery.ToList<Vehicle>();
                    DG_Details.ItemsSource = vehicleList;
                    DG_Details.Items.Refresh();
   }

但我想只检索4列而不是全部。需要帮忙!!

1 个答案:

答案 0 :(得分:4)

试试这个:

var vehicleList = (from v in context.Vehicles
                         select new
                         {
                              Number = v.LicencePlateNumber,
                              Make = v.Make,
                              Model = v.Model,
                              Year = v.PurchaseYear
                         }).ToList();
                    DG_Details.ItemsSource = vehicleList;
                    DG_Details.Items.Refresh();