g_b
g_b

Reputation: 12428

How to map multiple tables into one Entity in EF7

I have 2 tables in different schemas:

Base.Person
    ID
    FirstName
    LastName

Enrollment.Student
    PersonID
    StudentNo

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.

Upvotes: 0

Views: 2028

Answers (1)

natemcmaster
natemcmaster

Reputation: 26763

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
{
    [Key]
    public string StudentNo { get; set; }

    [ForeignKey("PersonId")]
    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 https://docs.efproject.net/en/latest/modeling/relationships.html#one-to-one

Upvotes: 1

Related Questions