1
votes

My Custom Entity:

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 Class:

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

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

I have two DbContexts (One default of AppUser and One I created):

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

When I run it just working with ApplicationDbContext it works fine and creates following table with all the relationships. enter image description here

My problem: is when I try to work with ADbContext with un-commented public DbSet<Order> OrderDbSet { get; set; }

{"One or more validation errors were detected during model generation:\r\n\r\n.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.\r\n.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined

Solutions I tried:

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

I am trying to have all tables created in one Database. I am using EF6.

2

2 Answers

0
votes

try this in OnModelCreating(DbModelBuilder modelBuilder):

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

refrence

0
votes

Solved :

In DbContext file, I added OrderDbSet within ApplicationDbContext class

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

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

    }
 }