2016-03-06 114 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

相关问题