如何在我的表AspNetUsers中显示引用的名称

时间:2016-10-02 22:33:44

标签: 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; }
}

这是ApplicationUser类的IdentityModels:

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>

错误:对象引用未设置为对象的实例。

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

Departamento.Provincia的{​​{1}}未加载,可能是Localidad本身。

您必须使用Localidad从上下文加载它,或者在另一个查询中显式加载它 例如:

Include