@mehdi selk , Based on your picture, I find that you are using .net core winform. Therefore, we need to use EF core to get data from database instead of Entityframework.
Please refer to the following steps to use ef-core in .net core winform app.
First, Please install the following nuget-package: (Please choose other type of ef core If you access other database)
Second, Please create model class and dbcontext class.
public class Student
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
}
public class MyDbContext:DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"connstr");
}
}
Third, Please execute the following command in your Package Manager Console window.
Add-Migration First
Update-Database
Finally, you could try the following code to insert data to database and show the data in datagridview.
private void Form1_Load(object sender, EventArgs e)
{
using (MyDbContext dbContext = new MyDbContext())
{
dbContext.Students.Add(new Student { Id=1001, Date=DateTime.Now, Name="test1" });
dbContext.Students.Add(new Student { Id=1002, Date=DateTime.Now, Name="test2" });
dbContext.Students.Add(new Student { Id=1003, Date=DateTime.Now, Name="test3" });
dbContext.SaveChanges();
}
}
MyDbContext dbContext = new MyDbContext();
private void button1_Click(object sender, EventArgs e)
{
var result = from c in dbContext.Students
select c;
dataGridView1.DataSource=result.ToList();
}
private void button2_Click(object sender, EventArgs e)
{
var result = from c in dbContext.Students
select new
{
c.Name,
c.Date
};
dataGridView1.DataSource= result.ToList();
}
Result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.