2016-03-06 112 views
0

具有在不同的模式2個表:我如何將多個表映射成一個實體在EF7

Base.Person 
    ID 
    FirstName 
    LastName 

Enrollment.Student 
    PersonID 
    StudentNo 

這涉及一個對一個。

現在在我的DbContext中,我想要一個名爲Students的DbSet,但我希望將其屬性映射到Person和Students。特別是,我想將Person.ID,Person.FirstName,Person.LastName,Student.StudentNo映射到我的Student類中。

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。

+0

你爲什麼不能引入Person類有名字,姓氏和標識?否則,我不確定是否有可能適合您的數據庫架構所需。 –

+0

爲了說明,是不同架構中的Student和Person表(如https://msdn.microsoft.com/en-us/library/ms189462.aspx中所述)還是表在不同的數據庫中? – natemcmaster

+0

@natemcmaster:相同的數據庫,不同的模式。 –

回答

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

相關問題