2016-10-02 3 views
0

내 테이블에서 참조한 도시의 이름을 표시하고 싶지만 AspNetUser를 수행 할 수 없습니다.내 테이블에 참조 이름을 표시하는 방법 AspNetUsers

public class IndexViewModel { 
    public bool HasPassword { get; set; } 
    public IList<UserLoginInfo> Logins { get; set; } 
    public string PhoneNumber { get; set; } 
    public bool TwoFactor { get; set; } 
    public bool BrowserRemembered { get; set; } 

    public string Nombre { get; set; } 
    public string Apellido { get; set; } 
    public string Direccion { get; set; } 
    public string Pais { get; set; } 
    public int LocalidadID { get; set; } 
    public string CodigoPostal { get; set; } 
    public string Telefono { get; set; } 
    public virtual Localidad Localidad { get; set; } 
} 

이 클래스 ApplicationUser :

public class ApplicationUser : IdentityUser { 
    public int LocalidadID { get; set; } 
    public string Nombre { get; set; } 
    public string Apellido { get; set; } 
    public string Direccion { get; set; } 
    public string Pais { get; set; }   
    public string CodigoPostal { get; set; }   
    public string Telefono { get; set; } 
    public System.DateTime FechaRegistro { get; set; } 

    // FOREIGN KEY 
    public virtual Localidad Localidad { get; set; } 

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     // Add custom user claims here 
     return userIdentity; 
    } 
} 

이 컨트롤러 지수는의 IdentityModels입니다

public async Task<ActionResult> Index(ManageMessageId? message) 
    { 

     if (User.Identity.Name.Equals("[email protected]")) 
      return RedirectToAction("GuestIndex"); 

     var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 
     var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); 
     var ctx = store.Context; 
     var usuario = manager.FindById(User.Identity.GetUserId()); 
     ApplicationDbContext db = new ApplicationDbContext(); 

     var model = new IndexViewModel 
     { 
      HasPassword = HasPassword(), 
      PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId()), 
      TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId()), 
      Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()), 
      BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(User.Identity.GetUserId()), 
      Direccion = usuario.Direccion, 
      Nombre = usuario.Nombre, 
      Apellido = usuario.Apellido, 
      Telefono = usuario.Telefono, 
      LocalidadID = usuario.LocalidadID, 
      //Localidades = db.Localidades.Where(l => l.LocalidadID==usuario.LocalidadID).Select(l => new {Nombre = l.Nombre}), 
      CodigoPostal = usuario.CodigoPostal 
     };    
     return View(model); 
    } 

그리고 내보기 내가 오류가 나에게 던져 :

이것은 IndexViewModels입니다
<p>Argentina, @Model.Localidad.Departamento.Provincia.Nombre</p> 

오류 : 개체 참조가 개체의 인스턴스로 설정되지 않았습니다.

+0

'Localidad'란 무엇입니까? – Hadee

+0

Localidad = 도시, Departamento = 부서, Provincia = 주. :-) – Max

답변

0

LocalidadDepartamento.Provincia은로드되지 않으며 Localidad 일 수 있습니다.

Localidad = (from l in db.Localidades where l.LocalidadID == usuario.LocalidadID select l).First<Localidad>() 

을 떠나 :

LocalidadID = db.Localidads.Include("Departamento.Provincia.").Where(a=>a.LocalidadId == usuario .LocalidadID) 
+0

감사하지만 다음 오류가 발생합니다. 'System.Linq.IQueryable '형식을 암시 적으로 'int'로 변환 할 수 없습니다. – Max

+0

대단히 감사합니다! 내가 shepherded, 내가 변환 오류를 보았을 때 나는이 방법을 사용했고 FOREIGN KEY를 할당하는 대신 "LocalidadID"가 LOCALITY 모델에 할당되었다. Localidad = (l.Localidades에서 l.LocalidadID == usuario.LocalidadID 선택 l) .First (), – Max

1

솔루션은 다음과 같은 줄을 추가했다 :

당신은 Include를 사용하여 컨텍스트에서로드 또는 다른 쿼리에서 명시 적으로 전을로드해야 기능은 다음과 같습니다 :

public async Task<ActionResult> Index(ManageMessageId? message) 
{ 

    if (User.Identity.Name.Equals("[email protected]")) 
     return RedirectToAction("GuestIndex"); 

    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 
    var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); 
    var ctx = store.Context; 
    var usuario = manager.FindById(User.Identity.GetUserId()); 
    ApplicationDbContext db = new ApplicationDbContext(); 

    var model = new IndexViewModel 
    { 
     HasPassword = HasPassword(), 
     PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId()), 
     TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId()), 
     Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()), 
     BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(User.Identity.GetUserId()), 
     Direccion = usuario.Direccion, 
     Nombre = usuario.Nombre, 
     Apellido = usuario.Apellido, 
     Telefono = usuario.Telefono, 
     LocalidadID = usuario.LocalidadID, 
     Localidad = (from l in db.Localidades where l.LocalidadID == usuario.LocalidadID select l).First<Localidad>(), 
     CodigoPostal = usuario.CodigoPostal 
    };    
    return View(model); 
} 
+0

Ready! ........ – Max