实体框架ApplicationUser代码首先多对多列表

时间:2016-11-29 17:19:58

标签: c# entity-framework

我有一个商店数据库。 商店

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public List<ApplicationUser> Administrators { get; set; } 
public List<ApplicationUser> Managers { get; set; } 

这是在ApplicationUser(AspNetUsers)中创建STK的FK,但是我需要能够让用户成为一个或多个商店的经理。

CREATE TABLE [dbo].[AspNetUsers](
[Id] [nvarchar](128) NOT NULL,
[Email] [nvarchar](256) NULL,
...
[Store_Id] [uniqueidentifier] NULL,
[Store_Id1] [uniqueidentifier] NULL,

您可以看到用户只能是一个Store_Id的管理员。我在Code-First方法中使用Entity Framework 6.1.3,并希望继续沿着这条路线前进。是否有一种简单的方法可以让EF以我想要的方式创建连接表,就像我首先使用数据库一样?

我的模型中的所有内容都达到了这一点,我的身份提供商和我所有的自定义废话都生活在同一个环境中。

1 个答案:

答案 0 :(得分:0)

对于同一条船上的任何人,我都可以使用以下方法。

public class Store : EntityModel
{
    public List<ApplicationUser> Administrators { get; set; }
    public List<ApplicationUser> Managers{ get; set; }
    ...
}

在IdentityModels中

public class ApplicationUser : IdentityUser
{
    public List<Store> StoreAdmin { get; set; }
    public List<Store> StoreManager { get; set; }
    ...
}

(这也在IdentityModels.cs中)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    modelBuilder.Entity<ApplicationUser>()
            .HasMany<Store>(u => u.StoreAdmin)
            .WithMany(s => s.Administrators)
            .Map(us =>
            {
                us.MapLeftKey("StoreId");
                us.MapRightKey("ApplicationUserId");
                us.ToTable("StoreAdministrators");
            });

        modelBuilder.Entity<ApplicationUser>()
            .HasMany<Store>(u => u.StoreManager)
            .WithMany(s => s.Managers)
            .Map(us =>
            {
                us.MapLeftKey("StoreId");
                us.MapRightKey("ApplicationUserId");
                us.ToTable("StoreManagers");
            });
     }

我在与StoreUser有两个“关系”的商店里被绊倒了。我看到的大部分内容都是COURSE&lt; =&gt;学生,而不是课程&lt; =&gt; GOODSTUDENTS和COURSE&lt; =&gt;学生类型的BADSTUDENTS。以上似乎工作得很漂亮。我并不是真的需要用户在我的应用程序中列出商店,但它就在那里。开心辞典。

感谢降级,DVK。喜欢这里的社区。