EF不会生成连接表

时间:2017-09-24 13:57:55

标签: c# sql asp.net-mvc entity-framework

我正在尝试连接两个表,但我不明白为什么它不会创建连接表。如果有人可以偷看,我会非常感激。

提前致谢! :)

编辑:包含datacontext。表User和Project已成功创建,但没有获得dbo.ProjectUser ...

用户模型:

public class User : IdentityUser
{

    public string FirstName { get; set; }

    public string SurName { get; set; }

    public string Address { get; set; }

    public string Domain { get; set; }

    public DateTime? TimeInDomain { get; set; }

    public DateTime? TimeInCompany { get; set; }

    public Project Project { get; set; }

    public ICollection<Project> Projects { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
    {

        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

项目模型:

public class Project
{
    public int Id { get; set; }

    public string Platform { get; set; }

    public DateTime ProjectStart { get; set; }

    public DateTime ProjectLaunch { get; set; }

    public string Description { get; set; }

    public bool IsActive { get; set; }

    public ICollection<User> Users { get; set; }
}

的DataContext:

public class DataContext : IdentityDbContext<User>
{
    public DbSet<Project> Projects {get; set; }

    public DataContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static DataContext Create()
    {
        return new DataContext();
    }

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>().ToTable("Users");
        modelBuilder.Entity<User>().ToTable("Users");
        modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
        modelBuilder.Entity<IdentityRole>().ToTable("Roles");
    }
}

1 个答案:

答案 0 :(得分:1)

User有两个属性引用Project

public Project Project { get; set; }
public ICollection<Project> Projects { get; set; }

默认情况下(User中没有Project属性),EF会将第一个属性视为一对多关系的一端。通常,它还会假设另一端是Project.Users。显然(我不知道),User.Projects的存在使EF确定所有关联彼此独立:User有两个FK到ProjectProject一个FK到User。我认为EF应该抛出一个模型构建器异常,告诉Project.Users的另一端是不明确的。

所以你必须告诉EF你打算如何共存协会:

modelBuilder.Entity<User>()
    .HasMany(u => u.Projects)
    .WithMany(p => p.Users)
    .Map(m => m.MapLeftKey("UserId").MapRightKey("ProjectId"));
modelBuilder.Entity<User>()
    .HasOptional(u => u.Project) // Or HasRequired
    .WithMany().Map(m => m.MapKey("ProjectId")).WillCascadeOnDelete(false);