簡體   English   中英

實體框架多對多關系導航屬性和ID

[英]Entity Framework many-to-many relationship navigation properties and ids

假設在數據模型中存在多對多關系。 我該如何設置它,以便ID列表急切加載,而導航屬性則是延遲加載?

在一對一關系中,我可以輕松地使用ForeignKey屬性來鏈接id和navigation屬性,但是我不確定是否存在鏈接集合的方法。 如何確保兩者一致?

public class User {
   public Guid Id { get; set; }
   public string Name { get; set; }

   public ICollection<User> FollwerIds { get; set; }
   public ICollection<User> FollwingIds { get; set; }
   public virtual ICollection<User> Followers { get; set; }
   public virtual ICollection<User> Following { get; set; }
}

public class UserContext: DbContext {
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        modelBuiler.Entity<User>()
            .HasMany(u => u.Followers)
            .WithMany(u => u.Following)
            .Map(m => m.MapLeftKey("FollowingUserId")
                .MapRightKey("FollowerUserId")
                .ToTable("UserFollowUser")
            );
    }
}

我想讓ASP.NET中的控制器始終返回帶有兩個用戶ID數組的User對象。 謝謝。

在多對多中,您不需要:

   public ICollection<User> FollwerIds { get; set; }
   public ICollection<User> FollwingIds { get; set; }

要使多對多關系正常工作,您需要:

public class User {
   public Guid Id { get; set; }
   public string Name { get; set; }

   public virtual ICollection<User> Followers { get; set; }
   public virtual ICollection<User> Following { get; set; }
}

public class UserContext: DbContext {
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        modelBuiler.Entity<User>()
            .HasMany(u => u.Followers)
            .WithMany(u => u.Following)
            .Map(m => m.MapLeftKey("FollowingUserId")
                .MapRightKey("FollowerUserId")
                .ToTable("UserFollowUser")
            );
    }
}

我相信這會如您所願。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM