【发布时间】:2016-04-13 19:52:24
【问题描述】:
我有一个 User 和 Following 类定义如下:
public class User : IdentityUser
{
public User()
{
Followers = new HashSet<Following>();
Following = new HashSet<Following>();
}
[Key]
public string ID { get; set; }
...
...
public virtual ICollection<Following> Followers { get; set; }
public virtual ICollection<Following> Following { get; set; }
}
public class Following
{
[Key]
public int ID {get;set;}
[MaxLength(100)]
public string follower { get; set; }
[MaxLength(100)]
public string following { get; set; }
public virtual User UserFollower { get; set; }
public virtual User UserFollowing { get; set; }
}
Following中的属性follower和following都是User对象的外键,代表关系。然后在 DBcontext 类中,我将覆盖 OnModelCreating:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany<Following>(u => u.Followers)
.WithOptional()
.HasForeignKey(c => c.following);
modelBuilder.Entity<User>()
.HasMany<Following>(u => u.Following)
.WithOptional()
.HasForeignKey(c => c.follower);
}
这非常适合获取用户的关注者和关注者:
User user = await UserManager.FindByIdAsync(ID);
List<Following> followers = user.Following.ToList();
我的基本问题是如何创建 UserFollower 和 UserFollowing 关系,以便将 Following 的这些属性中的每一个都映射到用户?
理想情况下,我可以按照以下方式做一些事情:
User user = await UserManager.FindByIdAsync(ID);
List<Following> followers = user.Following.ToList();
User userFollowing = followers[0].UserFollowing;
【问题讨论】:
标签: c# asp.net .net entity-framework