0

I am trying to establish foreign key to 2 classes using FluentAPI and bit confused on the way to implement it.

ApplicationUser uses ASP.NET Identity model and has UserId as string

public class ApplicationUser : IdentityUser
{
     public virtual List<UserProduct> Orders { get; set; }
}

Product that has a composite key on columns ProductID and ProductCategoryID

public class Product 
{
    public int ProductID { get; set; }
    public string ProductCategoryID { get; set; }

    public virtual List<UserProduct> Orders { get; set; }

    ...
}

and another class UserProduct that will have many-to-many relationship between ApplicationUser and Product table

public partial class UserProduct
{
    public string UserId { get; set; }

    public int ProductID { get; set; }
    public string ProductCategoryID { get; set; }

    public virtual ApplicationUser User { get; set; }

    public virtual Product Product { get; set; }
}

The FluentAPI code looks like

 modelBuilder.Entity<Product>().Property(t => t.ProductID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
 modelBuilder.Entity<Product>().HasKey(x => new { x.ProductID, x.ProductCategoryID  });

 modelBuilder.Entity<UserProduct>().HasKey(x => new {x.UserId, x.ProductID, x.ProductCategoryID});

How do I establish the foreign key relationship of UserProduct with ApplicationUser and Product?

GeekzSG
  • 943
  • 1
  • 11
  • 28
  • this link may be useful : http://stackoverflow.com/questions/29831729/asp-net-mvc-many-to-many-relationship-using-my-own-table – Iraj Aug 20 '15 at 05:43

1 Answers1

1

You can add the id-property (e.g. OrderId) to the class UserProduct and use this code to connect entities by foreign key.

modelBuilder.Entity<UserProduct>()
            .HasRequired(x => x.User) 
            .WithMany(u => u.Orders) 
            .HasForeignKey(x => x.OrderId);
Anton K
  • 176
  • 1
  • 5