MVC5 codefirst将用户添加到多对多关系中

时间:2013-10-22 10:02:13

标签: entity-framework ef-code-first asp.net-mvc-5 asp.net-identity

我正在使用带有codefirst的mvc5和用户帐户。

我有一个简单的要求,即用户可以属于多个商店,而企业可以拥有多个商店。

到目前为止,我有业务 - 许多商店正在运作,但我似乎无法弄清楚如何设置用户。

我的StoreModel

    public virtual Business Business { get; set; }

    public virtual ICollection<ApplicationUser> Employees { get; set; } 

我的BusinessModel

    public virtual ICollection<StoreModel> Stores { get; set; }

在我的背景下,我尝试过

public class ApplicationUser : IdentityUser
{
    //a user can belong to multiple stores
    public virtual ICollection<StoreModel> Stores { get; set; }
}

然而,当我尝试添加迁移时,生成的代码将更改我的表名,并确实在Store&amp;之间创建连接表。 AspNetUser

我的迁移似乎是

  public override void Up()
    {
        RenameTable(name: "dbo.Stores", newName: "ApplicationUserStoreModels");
        DropForeignKey("dbo.Stores", "ApplicationUser_Id", "dbo.AspNetUsers");
        DropIndex("dbo.Stores", new[] { "ApplicationUser_Id" });
        CreateIndex("dbo.ApplicationUserStoreModels", "ApplicationUser_Id");
        CreateIndex("dbo.ApplicationUserStoreModels", "StoreModel_StoreId");
        AddForeignKey("dbo.ApplicationUserStoreModels", "ApplicationUser_Id", "dbo.AspNetUsers", "Id", cascadeDelete: true);
        AddForeignKey("dbo.ApplicationUserStoreModels", "StoreModel_StoreId", "dbo.Stores", "StoreId", cascadeDelete: true);
        DropColumn("dbo.Stores", "ApplicationUser_Id");
    }

任何人都可以帮我做我需要做的工作吗?

1 个答案:

答案 0 :(得分:1)

你可以要么没有商店表,并在每个appuser和商家中放置一个列表,EF将建立你的多对多关系,或者你可以使用流畅的api来映射一切。应该像下面这样。

 public class Business
{
    public virtual ICollection<StoreModel> Stores { get; set; }
}
public class ApplicationUser : IdentityUser
{
    public virtual ICollection<StoreModel> Stores { get; set; }
}




public class StoreModel {
public string ApplicationUserId { get; set; }
public int BusinessId { get; set; }

public virtual Business Businesss { get; set; }
public virtual ApplicationUser ApplicationUsers { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   base.OnModelCreating(modelBuilder);
modelBuilder.Entity<StoreModel>().HasKey(e => new { e.ApplicationUserId, e.BusinessId});
}