How to map multiple tables into one Entity in EF7

entity-framework entity-framework-core


I have 2 tables in different schemas:



This is related one-to-one.

Now in my DbContext, I want to have a DbSet named Students but I want its properties mapped to Person and Students. In particular, I want to get Person.ID, Person.FirstName, Person.LastName, Student.StudentNo mapped into my Student class.

The Student class is:

public class Student
    public int ID { get; set;}
    public string FirstName { get; set;}
    public string MiddleName { get; set;}
    public string StudentNo { get; set;}

One additional question that I'd like to ask which is not related to my problem above but it will be clearer to ask if the example above is present, in designing your DbContext, is DbContext intended to make the whole of the database available to you or is it ok just to expose what you want? For example, in my question above, I don't have a Person DbSet.

3/6/2016 11:38:13 AM

Popular Answer

You cannot currently do this in EF 7 EF Core. However, you can model one to one relationships like this:

[Table("Student", Schema = "Enrollment")]
public class Student
    public string StudentNo { get; set; }

    public Person Person { get; set; }

    [Column("PersonID")] // <-- if your db is case sensitive
    public int PersonId { get; set; }

[Table("Person", Schema="Base")]
public class Person
    // [Key] - not needed as EF conventions will set this as the "key"
    [Column("ID")] // again, if case sensitive
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

// in code, use .Include to materialize dependent entities like so....
context.Students.Include(s => s.Person).Where(s => s.Person.FirstName == "Bob");

For more info on modeling, see

3/8/2016 3:24:27 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow