0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.