【问题标题】:In EF Code First, How to have ApplicationUser UserId as foreign key in a custom entity?在 EF Code First 中,如何将 ApplicationUser UserId 作为自定义实体中的外键?
【发布时间】:2019-05-03 18:59:44
【问题描述】:

我的自定义实体:

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){..}
}

我有两个 DbContexts(一个默认的 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&lt;Order&gt; OrderDbSet { get; set; } 使用 ADbContext 时

{“在模型生成期间检测到一个或多个验证错误:\r\n\r\n.IdentityUserLogin: : EntityType 'IdentityUserLogin' 没有定义键。定义此 EntityType 的键。\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。

【问题讨论】:

    标签: sql ef-code-first


    【解决方案1】:

    在 OnModelCreating(DbModelBuilder modelBuilder) 中试试这个:

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

    refrence

    【讨论】:

      【解决方案2】:

      已解决:

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

      public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
      {
          public DbSet<Order> OrderDbset { get; set; }
      
          public ApplicationDbContext()
              : base("DefaultConnection", throwIfV1Schema: false)
          {
      
          }
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多