与ASP.NET AspNetUser表的多对多关系被忽略

时间:2018-02-18 23:43:54

标签: asp.net entity-framework

一个用户可以是许多项目的成员,而项目可以有多个成员。

ASP.NET标识ApplicationUser

public class ApplicationUser : IdentityUser
{
    [Display(Name = "Projekt")]
    public virtual ICollection<Project> Projects { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

我的Project

[Table("Projects")]
public class Project : IValidatableObject
{
    [Key]
    public int ID { get; set; }
    [Required, StringLength(128), Display(Name = "Projektname"), Index(IsUnique = true)]
    public string Name { get; set; }

    // working one-to-many relation
    [Display(Name = "Projektleiter")]
    public string LeaderID { get; set; }
    [ForeignKey("LeaderID"), Display(Name = "Projektleiter")]
    public virtual ApplicationUser ApplicationUser { get; set; }

    // many-to-many relation gets ignored
    [Display(Name = "Mitarbeiter")]
    public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        return new List<ValidationResult>();
    }
}

没有创建多对多表。整个关系被忽略了。但LeaderID的工作正在......

有人能告诉我这里缺少什么吗? (我用谷歌搜索了它,我多次删除了整个数据库,我尝试了所有我找到的,没有运气......)

1 个答案:

答案 0 :(得分:0)

我会将ApplicationUser实体与您对项目的任何逻辑分开,并创建另一个名为Person的实体。

public class Person
{
//Constuctor : always intantiate lists in ctor
public Person()
{
       Projects = new List<Project>();
}

 public int Id { get; set; }
 public string IdentityId { get; set; } //gets guid from AppUser table
 public ApplicationUser Identity { get; set; }  // navigation property
 public List<Project> Projects { get; set; }
 //public int ProjectId {get; set;}//-----optional

}

所以在项目中知道我们做同样的事情:

[Table("Projects")]
public class Project : IValidatableObject
{
        //Constuctor : always intantiate lists in ctor
    public Project()
    {
           Persons = new List<Person>();
    }
    [Key]
    public int ID { get; set; }
    [Required, StringLength(128), Display(Name = "Projektname"), Index(IsUnique = true)]
    public string Name { get; set; }

    public string PersonId { get; set; }  //nav property
    public List<Persons> Persons { get; set; }
    public Person Person { get; set; } //context will be aware that this is fk

   [Display(Name = "Projektleiter")]
   public string LeaderID { get; set; }




    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        return new List<ValidationResult>();
    }
}

为dbcontext类中的两个实体添加数据库集。 现在,您希望获得一个包含项目列表的人员,反之亦然。为此,我们使用include:

var x = myContext.Persons.Include(x => x.Projects);
var d = x.ToList();

//您可以使用applicationUser实体而不是person,但随着项目的增长,会发生不好的事情。