Как отобразить имя ссылки в моей таблице AspNetUsers

#asp.net-mvc #asp.net-identity #asp.net-mvc-viewmodel

#asp.net-mvc #asp.net-identity #asp.net-mvc-viewmodel

Вопрос:

Я хочу отобразить название города, на который я ссылался в своей таблице, но я не могу AspNetUser как. Это IndexViewModels:

  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; }
}
  

Это IdentityModels класса 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;
    }
}
  

Это индекс контроллера

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

        if (User.Identity.Name.Equals("guest@guest.com"))
            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);
    }
  

И на мой взгляд, я выдаю ошибку:

 <p>Argentina, @Model.Localidad.Departamento.Provincia.Nombre</p>
  

Ошибка: ссылка на объект не установлена для экземпляра объекта.

Комментарии:

1. Что такое Localidad ?

2. Localidad = город, Departamento = департамент, Провинция = Штат. 🙂

Ответ №1:

Решением было добавить следующую строку:

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

Оставляя функцию такой:

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

    if (User.Identity.Name.Equals("guest@guest.com"))
        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);
}
  

Ответ №2:

Часть Departamento.Provincia Localidad не будет загружена, и, возможно Localidad , сама.

Вы должны загрузить его из контекста, используя Include или явно загружая его в другом запросе, например:

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

Комментарии:

1. спасибо, но выдает следующую ошибку: не удается неявно преобразовать тип ‘System.Linq. IQueryable Модели. Localidad>’ в ‘int’

2. Большое вам спасибо! Я пастух, я использовал этот способ, поскольку я искал ошибку преобразования, и вместо назначения ВНЕШНЕГО КЛЮЧА «LocalidadID» присваивается ЛОКАЛЬНОСТИ модели. Localidad = (из l в db.Localidades где l.LocalidadID == обычно. LocalidadID выберите l). Сначала<Localidad>(),