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