0

So I have a Users class and a products class.

I am using Code first approach and trying to make it so that I can add in products and I can add in users and then have the relationship mapped between the two objects without having a foreign key relationship.

So in essence the user will have more than one product but the products will be defined. I would do this normally in a database with a lookup table mapping the two of them but I can not for the life of me get Entity to do this functionality and am considering scrapping it and doing Database first design.

For the purposes of this question you can consider a user just a POCO with an ID and Products a POCO With an id.

I feel like I am dancing around this issue while searching but I can't find anything that solves it so sorry if the answer is out there already.

4

2 回答 2

1

对象关系取决于Foreign Keys,至少我知道它应该是这样的。在您的情况下,您正在寻找one-to-many(即一个拥有许多产品的用户)。

尝试这个;

Public class User 
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int UserId { get; set; }

   public string Name { get; set; }

   public virtual ICollection<Product> Products { get; set; }
}

Public class Product
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int ProductId{ get; set; }

   [ForeignKey("User"), DatabaseGenerated(DatabaseGeneratedOption.None)]
   public int? UserId{ get; set; } 

   public string Name { get; set; }

   public virtual User User { get; set; }
}
于 2013-05-07T23:33:52.623 回答
0

答案显然是 Fluent API 框架。

您必须在您的上下文中覆盖此方法

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().
              HasMany(c => c.ActiveProducts).
              WithMany(p => p.UsersOfProduct).
              Map(
               m =>
               {
                   m.MapLeftKey("UserId");
                   m.MapRightKey("ProductId");
                   m.ToTable("ProductUsers");
               });
        }

我仍然没有真正了解它的全部“HasMany,WithMany”语法,但这就是它所做的。您必须这样做,以便它知道创建关系表,而不是默认将 ID 列连接到对象上。

于 2013-05-08T01:45:55.280 回答