我试图实施看起来很常见的情况 - 两个用户之间的友谊关系。我认为模型是不言自明的。 Friendship
需要有2个用户,还有一些关于该关系的数据,并且用户拥有Friendships
属性,该属性由他们所属的任何友谊填充,为User1
或User2
。我无法找到一个更好的方法来命名这两个用户。这是我的模特:
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完成此操作?特别感谢任何可以提供帮助的人。
答案 0 :(得分:2)
您正在遇到multiplicity constraint。 Friendship
类有两个用户从ApplicationUser
- &gt;创建一个周期。 Friendship
- &gt; ApplicationUser
。要解决此问题,请删除User1
和User2
属性,然后添加一个集合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();
}