有多个约定用于实现Many to Many
和One to Many
关系entity framework
。将尝试提及所有。希望这些会有所帮助。
更新(因为 OP 想要多对多):多对多 关系
公约 1:
两个模型中的集合导航属性
public class UserAccount
{
public int Id { get; set; }
public string Username { get; set; }
public ICollection<Challenge> Challenges { get; set; }
}
public class Challenge
{
public int Id { get; set; }
public string ChallengeId {get; set;}
public string Name { get; set; }
public string Description { get; set; }
public ICollection<UserAccount> UserAccounts { get; set; }
}
实现相同目标的其他方法
mb.Entity<UserAccount>()
.HasMany(r => r.Challenges)
.WithMany()
.Map(m =>
{
m.MapLeftKey("UserAccountId");
m.MapRightKey("ChallengeId");
m.ToTable("UserAccountChallenge"); //Junction Table
});
一对多关系
公约 1:
这可以通过UserAccount
在Challenge
public class Challenge
{
public int Id { get; set; }
public string ChallengeId {get; set;}
public string Name { get; set; }
public string Description { get; set; }
public UserAccount UserAccount{get;set;}
}
公约 2:
另一个约定是在集合导航属性中包含
UserAccount
public class UserAccount
{
public int Id { get; set; }
public string Username { get; set; }
public ICollection<Challenge> Challenges { get; set; }
}
公约 3:
两端包含导航属性也会导致一对多的关系
public class Challenge
{
public int Id { get; set; }
public string ChallengeId {get; set;}
public string Name { get; set; }
public string Description { get; set; }
public UserAccount UserAccount{get;set;}
}
public class UserAccount
{
public int Id { get; set; }
public string Username { get; set; }
public ICollection<Challenge> Challenges { get; set; }
}
公约 4:
两端完全定义的关系将创建一对多的关系
public class Challenge
{
public int Id { get; set; }
public string ChallengeId {get; set;}
public string Name { get; set; }
public string Description { get; set; }
public int UserAccountId { get; set; }
public UserAccount UserAccount{get;set;}
}
使用 Fluent API 配置一对多关系
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// configures one-to-many relationship
modelBuilder.Entity<UserAccount>()
.HasRequired<Challeng>(s => s.ChallengId)
.WithMany(g => g.UserAccount)
.HasForeignKey<int>(s => s.ChallengId);
}