【问题标题】:MVC5 codefirst adding a user to many-many relationshipMVC5 codefirst 将用户添加到多对多关系
【发布时间】:2013-10-31 03:15:57
【问题描述】:

我将 mvc5 与 codefirst 和用户帐户一起使用。

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

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

我的店铺模型

    public virtual Business Business { get; set; }

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

我的商业模式

    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 和 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");
    }

任何人都可以帮助我完成这项工作吗?

【问题讨论】:

  • 你可能需要写一些FluentAPI 来得到你想要的,就我个人而言,如果不使用@987654326,我永远无法按照我想要的方式进行多对多工作@
  • @SOfanatic 当我们使用 fluent api 时,我们需要在模型中指定导航属性吗?

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


【解决方案1】:

您可以没有商店表并在每个应用程序用户和企业中放置一个列表,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});
}

【讨论】:

  • 我们在使用fluent api时需要在models中指定导航属性吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
相关资源
最近更新 更多