[英]Many-to-many relationship between the same class
我正在嘗試實現一個似乎很常見的情況-2個用戶之間的友誼關系。 我認為這些模型是不言自明的。 Friendship
需要兩個用戶以及一些有關該關系的數據,並且用戶具有一個Friendships
屬性,該屬性由他們所屬的任何友誼(如User1
或User2
)填充。 我想不出一種更好的方式來命名2個用戶。 這是我的模型:
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
中配置關系的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完成此操作? 特別感謝任何可以提供幫助的人。
您遇到了多重約束 。 Friendship
類有兩個用戶,它們從ApplicationUser
> Friendship
> 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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.