Entity framework and Classes

Refresh

December 2018

Views

206 time

1

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

2 answers

1

Don't have a seperate context for each DbSet. I.e

class MyDbContext : DBContext
{
   public DbSet<Course> Courses{get;set;}
   public DbSet<Assignment> Assignments{get;set;}
}
3

Both entities need to be in the same context.

public class CoursesContext: DbContext
{
   public DbSet<Assignment> Assignments {get; set;}    
   public DbSet<Course> Courses {get; set;}
}

You can add an Assignment navigation property to filter on a foreign key:

public class Course
{
  [Key]
  public virtual int CourseID {get; set;}
  public virtual string CourseName {get; set;}
  public virtual Assignment {get; set;}
}

Then you can query like so:

var staffId = 
      from c in a.Course
      where c.CourseID == 1001
      select c.Assignment.StaffID;