如何判断保存了哪个子类?

时间:2014-07-22 17:24:19

标签: c# asp.net-mvc entity-framework

我有一个带有2个子类的模型:

public class User
{
    public string eRaiderUsername { get; set; }
    public int AllowedSpaces { get; set; }
    public ContactInformation ContactInformation { get; set; }
    public Ethnicity Ethnicity { get; set; }
    public Classification Classification { get; set; }
    public Living Living { get; set; }
}

public class Student : User
{
    public Student()
    {
        AllowedSpaces = AppSettings.AllowedStudentSpaces;
    }
}

public class OrganizationRepresentative : User
{
    public Organization Organization { get; set; }

    public OrganizationRepresentative()
    {
        AllowedSpaces = AppSettings.AllowedOrganizationSpaces;
    }
}

public class ContactInformation
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string CellPhoneNumber { get; set; }
}

public enum Ethnicity
{
    AfricanAmerican,
    AmericanIndian,
    Asian,
    Black,
    Hispanic,
    NativeHawaiian,
    NonResidentAlien,
    White
}

public enum Classification
{
    Freshman,
    Sophomore,
    Junior,
    Senior,
    GraduateStudent
}

public enum Living
{
    OnCompus,
    OffCampus
}

使用这些初始化程序(大多数情况下)保存得很好:

 var students = new List<Student>
 {
     new Student{ eRaiderUsername="somestudent", ContactInformation=new ContactInformation{FirstName="Some", LastName="Student", EmailAddress="student@example.com", CellPhoneNumber="1234567890"}, Classification=Classification.Junior, Ethnicity=Ethnicity.Hispanic, Living=Living.OffCampus }
 };
 students.ForEach(s => context.Users.Add(s));
 context.SaveChanges();

 var orgReps = new List<OrganizationRepresentative>
 {
     new OrganizationRepresentative{ eRaiderUsername="somerep", ContactInformation=new ContactInformation{FirstName="Some", LastName="Representative", EmailAddress="orgrep@example.com", CellPhoneNumber="0987654321"}, Classification=Classification.Freshman, Ethnicity=Ethnicity.White, Living=Living.OnCompus, Organization=context.Organizations.Find(1) }
 };
 orgReps.ForEach(o => context.Users.Add(o));
 context.SaveChanges();

所有枚举都没有保存(对此的建议也很棒)。但其他一切都很好。

我注意到Entity添加了一个带有子类名称的Discriminator列。我如何使用它来仅查询学生,只查询组织代表,或者只是告诉当前对象是控制器或视图中的学生或组织代表?

1 个答案:

答案 0 :(得分:1)

鉴别器列由EF内部使用,以确定要实例化的对象类型。

例如,您可以直接查询学生。 context.Set<Student>.Find(id)。组织代表也是如此。或者您可以查询任何用户context.Set<User>.Find(id)

如果您查询学生,但是传递了组织代表的ID,那么EF将返回null,因为该ID不属于学生。