假设在数据模型中存在多对多关系。如何设置它以便id的列表被急切加载并且导航属性是延迟加载的?
在一对一的关系中,我可以轻松地使用ForeignKey属性来链接id和导航属性,但我不确定是否有链接集合的方法。我怎样才能确保两者一致?
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中的控制器始终返回带有两个User Ids数组的User对象。 谢谢。
答案 0 :(得分:0)
在多对多中你不需要这个:
public partial class ProgressForm : Form
{
public ProgressForm()
{
InitializeComponent();
this.TopMost = true;
}
public void SetProgress(int progress)
{
this.progressBar1.Value = progress;
// Allow the form to be repainted
Application.DoEvents();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ProgressForm progressForm = new ProgressForm();
void Task2()
{
ShowProgress(0);
for (int i = 0; i < 10; i++ )
{
System.Threading.Thread.Sleep(1000);
ShowProgress(i * 10);
}
HideProgress();
}
void ShowProgress(int progress)
{
if (!progressForm.Visible)
progressForm.Show();
progressForm.SetProgress(progress);
}
void HideProgress()
{
progressForm.Hide(); // or Close, it depends from app logic
}
private void button1_Click(object sender, EventArgs e)
{
Task2();
}
}
答案 1 :(得分:0)
要使多对多关系有效,您需要:
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")
);
}
}
我相信这会按你的意愿运作。