同一类之间的多对多关系

时间:2015-01-29 16:12:39

标签: c# entity-framework

我试图实施看起来很常见的情况 - 两个用户之间的友谊关系。我认为模型是不言自明的。 Friendship需要有2个用户,还有一些关于该关系的数据,并且用户拥有Friendships属性,该属性由他们所属的任何友谊填充,为User1User2。我无法找到一个更好的方法来命名这两个用户。这是我的模特:

public class Friendship : Entity
{
    public ApplicationUser User1 { get; set; }
    public ApplicationUser User2 { get; set; }
    ...
}

public class ApplicationUser : IdentityUser
{
    public virtual List<Friendship> Friendships { get; set; }
    ...
}

我尝试在OnModelCreating中配置关系:

modelBuilder.Entity<ApplicationUser>()
    .HasMany(x => x.Friendships)
    .WithRequired()
    .Map(t => t.MapKey("User1_Id", "User2_Id"));

我认为我没有正确配置。这是我尝试从此创建迁移时遇到的错误:

The specified association foreign key columns 'User1_Id, User2_Id' are invalid. The number of columns specified must match the number of primary key columns.

是否可以使用ef6完成此操作?特别感谢任何可以提供帮助的人。

1 个答案:

答案 0 :(得分:2)

您正在遇到multiplicity constraintFriendship类有两个用户从ApplicationUser - &gt;创建一个周期。 Friendship - &gt; ApplicationUser。要解决此问题,请删除User1User2属性,然后添加一个集合ICollection<ApplicationUser> Users

DTO:

public class ApplicationContext : DbContext
{
    public ApplicationContext()
        : base("ApplicationContext")
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Relationship> Relationships { get; set; }
}

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

public class User : Entity
{
    public string Name { get; set; }
    public virtual ICollection<Relationship> Relationships { get; set; }
}

public class Relationship : Entity
{
    public virtual ICollection<User> Users { get; set; }
}

样品:

var bob = new User
{
    Name = "Bob",
    Relationships = new List<Relationship>()
};

var fred = new User
{
    Name = "Fred",
    Relationships = new List<Relationship>()
};

var relationship = new Relationship
{
    Users = new List<User>
    {
        bob,
        fred
    }
};

bob.Relationships.Add(relationship);
fred.Relationships.Add(relationship);

using(var context = new ApplicationContext())
{
    context.Users.Add(bob);
    context.Users.Add(fred);
    context.Relationships.Add(relationship);

    context.SaveChanges();
}
豫ICP备18024241号-1