在EF Code First中,如何在自定义实体中将ApplicationUser UserId作为外键?

时间:2018-12-02 05:04:09

标签: sql ef-code-first

我的自定义实体:

public class Order
    {
        [Key,Column(Order=0)]
        public int OrderId { get; set; }
        //Other properties
        public string UserId { get; set; }
        [ForeignKey("UserId")]
        public virtual ApplicationUser User { get; set; }
     }

ApplicationUser类:

public class ApplicationUser : IdentityUser
{
    //one to many relation
    public virtual List<Sandwich.Order>Order { get; set; }

   public async Task<ClaimsIdentity> 
   GenerateUserIdentityAsync(UserManager<ApplicationUser> manager){..}
}

我有两个DbContext(一个是默认的AppUser,另一个是我创建的):

  public class ADbContext : DbContext
{
    public ADbContext() : base("DefaultConnection")
    {
    }

    public DbSet<Toppings> ToppingsDbset { get; set;}
    //I had to comment the line below to in order to work with ToppingDBset but then I can't work with OrderDBSet
    //public DbSet<Order> OrderDbSet { get; set; }

}
//Default AppDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {

    }

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

当我运行它时,仅使用ApplicationDbContext即可正常工作,并创建具有所有关系的下表。 enter image description here

我的问题:是当我尝试使用未注释public DbSet<Order> OrderDbSet { get; set; }的ADbContext时

{“在模型生成过程中检测到一个或多个验证错误:\ r \ n \ r \ n.IdentityUserLogin :: EntityType'IdentityUserLogin'没有定义密钥。为此实体类型定义密钥。\ r \ n.IdentityUserRole :::EntityType'IdentityUserRole'没有定义键

我尝试过的解决方案:

//Adding following method on ADbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    }

我正在尝试在一个数据库中创建所有表。我正在使用EF6。

2 个答案:

答案 0 :(得分:0)

在OnModelCreating(DbModelBuilder modelBuilder)中尝试:

  

modelBuilder.Entity()           .HasMany(c => c.Order)           .WithOne(e => e.ApplicationUser);

refrence

答案 1 :(得分:0)

已解决:

在DbContext文件中,我在ApplicationDbContext类中添加了OrderDbSet

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Order> OrderDbset { get; set; }

    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {

    }
 }