简体   繁体   中英

using LINQ from Database to List in c#

i have a t_my_class table structure like below (MySql table)

id     class     group     age     name     surname
1      9         A         18      sarah    brown
2      10        B         20      joe      sanders
3      8         A         17      elisa    connor
4      10        C         23      sandra   brown

and i have a struct and a list of that struct

struct MyClass
{
   int id;
   string class;
   string group;
   int age;
   string name;
   string surname;
}
List<MyClass> Students = new List<MyClass>();

Now, can u tell me which LINQ query to use to select all data from t_my_class table to Students List.

Firstly, that should almost certainly not be a struct - it should be a class . Now, you have a couple of choices; if you do already have a LINQ-enabled ORM hooked up, then it should be simply:

var students = myContext.Students.ToList();

If you aren't already using an ORM tool then a micro-ORM might help, for example dapper-dot-net works with MySql AFAIK, allowing:

var students = connection.Query<Student>("select * from t_my_class").ToList();

With:

class Student
{
   public int Id {get;set;}
   public string Class {get;set;}
   public string Group {get;set;}
   public int Age {get;set;}
   public string Name {get;set;}
   public string Surname {get;set;}
}
var students = from std in Students
               select std.

在此处输入图片说明

More : Learn SQL to LINQ (Visual Representation)

var students = from p in entities.t_my_class 
select p;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM