使用ASPNETUSER表电子邮件字段作为另一个表(主外键)中的主键

时间:2016-06-07 16:41:34

标签: c# entity-framework asp.net-mvc-4 asp.net-identity ef-migrations

我一直在努力做到这一点,我无法找到解决方案。感谢任何帮助,链接到一个示例或简单的教程,我只是想熟悉MVC。如果这已经得到解答,我很抱歉,但我找不到合适的解决方案。 我想使用存储在Identity ASPNETUSER表中的电子邮件字段作为另一个表中的外部主键。这是我正在玩的一些代码,看看我是否让它工作,但得到了这个错误: "运行所选代码生成器时出错:'无法检索' ZooMenagerie.Models.UserDetails'的元数据。不支持每种类型的多个对象集。对象设置' ApplicationUsers'和'用户'都可以包含类型为' ZooMenagerie.Models.ApplicationUser'。'"''' 在我尝试构建我的UserDetails模型之后出现此错误,我选择的数据上下文类称为ApplicationDbContext(ZooMenagerie.Models)。 N.B - 我有两个Context类,一个是MVC自带的' ApplicationDbContext'和#ZooMenagerieContext'。我指出ApplicationDbContext指向同一个数据库,如果这是我做错了,请告诉我。

IdentityModels.cs

using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace ZooMenagerie.Models
{
// You can add profile data for the user by adding more properties to your          ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
    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 virtual UserDetails UserDetails { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("name=ZooMenagerieContext", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public System.Data.Entity.DbSet<ZooMenagerie.Models.UserDetails> UserDetails { get; set; }

    public System.Data.Entity.DbSet<ZooMenagerie.Models.ApplicationUser> ApplicationUsers { get; set; }
}
}    

UserDetails.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace ZooMenagerie.Models
{
public class UserDetails
{
    [Key, ForeignKey("Id")]
    public string knumber { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

}

1 个答案:

答案 0 :(得分:1)

我做了一个我重命名的解决方法:

  public virtual ApplicationUser ApplicationUser { get; set; }

  public virtual ApplicationUser User { get; set; }

然后重构代码我将我的代码搭建了,删除了

public System.Data.Entity.DbSet<ZooMenagerie.Models.ApplicationUser> ApplicationUsers { get; set; }

转到我的控制器并将ApplicationUser的任何使用更改为User,因此例如在我的索引类中看起来像这样:

public ActionResult Index()
    {
        var userDetails = db.UserDetails.Include(u => u.User);
        return View(userDetails.ToList());
    }

我的控制器全部使用User而不是applicationuser。