如何在EF7中将多个表映射到一个实体

时间:2016-03-06 11:38:14

标签: entity-framework entity-framework-core

我有两个不同模式的表:

Base.Person
    ID
    FirstName
    LastName

Enrollment.Student
    PersonID
    StudentNo

这是一对一的关联。

现在在我的DbContext中,我想要一个名为Students的DbSet,但我希望它的属性映射到Person和Students。特别是,我想将Person.ID,Person.FirstName,Person.LastName,Student.StudentNo映射到我的Student类。

学生班是:

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

我想问的另一个问题与我上面的问题无关,但在设计DbContext时,问上面的例子是否存在会更清楚DbContext是否打算制作整个数据库可以使用或者只是暴露你想要的东西?例如,在我上面的问题中,我没有Person DbSet。

1 个答案:

答案 0 :(得分:1)

您目前无法在 EF 7 EF Core中执行此操作。但是,您可以建模这样的一对一关系:

[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");

有关建模的更多信息,请参阅https://docs.efproject.net/en/latest/modeling/relationships.html#one-to-one