Reputation: 41
I have a Windows Forms application and want to get information from multiple tables of my database in the single dataGridView area.
I am trying to do it without SqlConnection
and SqlDataAdapter
, so the connection will be proceed through Entity Framework
DBContext db = new DBContext
Is it possible to do so?
I have three tables:
User:
UserID,
Name
System:
SysID,
SysType
Activities:
ActivID,
UserID (FK)
SysID (FK)
Date,
Version,
Changes
My code:
using DBContext db = new DBCntext())
{
dataGridView.DataSource = db.Table.ToList<Table>();
}
So I would write in case of only one table, but would it be possible to concatenate two or more tables without do it right in the database?
At the end I want to get User+System+Activities tables within one dataGridView.
Upvotes: 0
Views: 1124
Reputation: 12304
If your class is properly defined like this:
public class Activity
{
public int ActivityID { get; set; }
public string Version{ get; set; }
public DateTime Date { get; set; }
public string Changes { get; set; }
public int UserID { get; set; }
public User User { get; set; } // navigation property for User
public int SystemID { get; set; }
public System System { get; set; } // navigation property for System
}
Now you can write a query like:
using DBContext db = new DBCntext())
{
dataGridView.DataSource = db.Activitys
.Include(a => a.User)
.Include(a => a.System)
.Select(a => new MyModel {
MyModel.ActivityID = a.ActivityID,
MyModel.Version= a.Version,
MyModel.Date = a.Date ,
MyModel.Changes = a.Changes,
MyModel.UserName = a.User.Name,
MyModel.SysType= a.System.SysType
})
.ToList();
}
If you have not defined navigation properties, then you could use a LINQ Join.
Upvotes: 1