I am trying to learn Entity framework. Say, I have the following classes
class Course
{
[Key]
public virtual int CourseID {get; set;}
public virtual string CourseName {get; set;}
}
class CourseDBContext:DBContext
{
public DbSet<Course> Courses{get;set;}
}
Then I can use Linq to query the database as shown below
using (CourseDBContext a = new CourseDBContext())
{
var b = from c in a.Course
where c.CourseID == 1001
select c;
var d = b.FirstOrDefault();
if(d != null)
Console.WriteLine(d.CourseName);
}
This works fine. Now if I add a second class
class Assignment
{
[Key]
public virtual int CourseID {get; set;}
public virtual int StaffID {get; set;}
}
class AssignmentDBContext:DBContext
{
public DbSet<Assignment> Assignments{get;set;}
}
Now, How can I use Linq to select and display the CourseName and StaffID associated with CourseID = 1001?
The example above is contrived and so the table design and fields are irrelevant. I just want to know how to query the data between two classes from two different database tables using Entity Framework and Linq.
Thanks
Both entities need to be in the same context.
You can add an Assignment navigation property to filter on a foreign key:
Then you can query like so: