1
我正在用Friend函数构建一个社交网络。 我的想法是,我已经有默认ApplicationUser类,所以我创建了一个新的表名为朋友实体框架代码优先,同一个表上的多对多关系
public class Friend
{
[Key]
[Column(Order = 1)]
public string SenderId { get; set; }
[Key]
[Column(Order = 2)]
public string ReceiverId { get; set; }
//Status == true : Friend request accepted
//Status == false : Friend request not accepted
public bool Status { get; set; }
}
在ApplicationUser,我定义2个导航性能发件人并接收机 (链接到朋友表)
public class ApplicationUser : IdentityUser
{
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
public bool Gender { get; set; }
[StringLength(255)]
public string Address { get; set; }
[StringLength(255)]
public string Job { get; set; }
[StringLength(255)]
public string Image { get; set; }
public DateTime Birthday { get; set; }
public ICollection<ApplicationUser> Senders { get; set; }
public ICollection<ApplicationUser> Receivers { get; set; }
}
最后在ApplicationDbContext中,我使用Flue声明了2个表之间的关系NT阿比
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Friend> Friends { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUser>()
.HasMany(a => a.Senders)
.WithMany(a => a.Receivers)
.Map(m =>
{
m.MapLeftKey("ReceiverId");
m.MapRightKey("SenderId");
m.ToTable("Friends");
});
base.OnModelCreating(modelBuilder);
}
}
但是当我添加迁移,它会创建2个表像这样,和他们都不是我需要的东西(一个没有外键,一个没有状态属性)
public override void Up()
{
CreateTable(
"dbo.Friends1",
c => new
{
SenderId = c.String(nullable: false, maxLength: 128),
ReceiverId = c.String(nullable: false, maxLength: 128),
Status = c.Boolean(nullable: false),
})
.PrimaryKey(t => new { t.SenderId, t.ReceiverId });
CreateTable(
"dbo.Friends",
c => new
{
SenderId = c.String(nullable: false, maxLength: 128),
ReceiverId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.SenderId, t.ReceiverId })
.ForeignKey("dbo.AspNetUsers", t => t.SenderId)
.ForeignKey("dbo.AspNetUsers", t => t.ReceiverId)
.Index(t => t.SenderId)
.Index(t => t.ReceiverId);
}
那我该怎么做:(我搜索互联网上,这似乎合法但它不起作用
你刚才救了我的一天,谢谢! – LaXuanLinh
还有一个问题,我如何检索一个用户的朋友列表? – LaXuanLinh
我需要一个ApplicationUser的列表,它们是另一个ApplicationUser的朋友。所以我通过它的ID和查询如下 – LaXuanLinh