2014-10-17 3 views
-1

인증 된 사용자의 역할을 확인하는 컨트롤러가 있습니다. 역할에 기초하여 클래스의 인스턴스를 생성해야합니다. 예를 들어 역할이 "학생"인 경우 Student 클래스의 인스턴스를 만들어야합니다. 나는 이런 식으로 시도했지만 작동하지 않습니다 :알 수없는 유형의 인스턴스 만들기 및 함께 작업 MVC의

private object CurrentUser; 

switch(Role) 
{ 
    case "student": 
    CurrentUser = context.Students.FirstOrDefault(std => std.UserId == WebSecurity.CurrentUserId); 
    break; 
    . 
    . 
    . 
} 

그러나 학생 속성을 정의 할 수 없습니다. 예를 들어 CurrentUser을 얻고 싶다면 firstname 속성을 사용할 수 없습니다. 어떻게 CurrentUser을 이식 할 수 있습니까?

+2

확실하지 4 명 "당신이 무엇을 요구 불분명 '으로 닫 투표 이유. 그는'Student'의 인스턴스를'object' 타입의 변수에 할당하고'Student'의 속성이 왜 유용하지 않은지 이해하지 못합니다. –

답변

2

CurrentUser를 object 유형으로 정의했습니다. 캐스트하지 않는 한 속성은 Student이 아닙니다.

private object CurrentUser; 

인터페이스 또는 공통 기본 클래스를 사용할 수 있습니다.

public class Person 
{ 
    public string FirstName { get; set; } 
} 

public class Student : Person 
{ 
    // Add special properties for students 
} 

public class Professor : Person 
{ 
    // Add special properties for professors 
} 

그런 다음 CurrentUser에 사용할 수 Person에 사용할 수있는 모든 속성을

private Person CurrentUser; 

를 사용합니다. 당신은 단지 Student에 속성에 액세스하는 데 필요한 경우는 다음과 같이 캐스팅 수 :

((Student)CurrentUser).SomePropertyOfStudent 
+0

감사합니다. Eric. 나는 또한 학생 클래스를 EF 첫 번째 코드로 사용하여 데이터베이스를 사용하고있다. 기본 클래스를 사용하더라도 데이터베이스에 영향을주지 않습니까? – Mohammadalijf

+1

EF 코드는 먼저 기본 클래스 (또는 전체 클래스 계층 구조)를 완전히 지원합니다. http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph를 참조하십시오. –

관련 문제