我所做的就是按照他们在页面上写的做
https://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration
.在他们的例子中,他们有以下两类:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
然后他们制作了以下课程,通过多对多关系将他们联系起来:
public class BookCategory
{
public int BookId { get; set; }
public Book Book { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
然后它们有以下配置:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BookCategory>()
.HasKey(bc => new { bc.BookId, bc.CategoryId });
modelBuilder.Entity<BookCategory>()
.HasOne(bc => bc.Book)
.WithMany(b => b.BookCategories)
.HasForeignKey(bc => bc.BookId);
modelBuilder.Entity<BookCategory>()
.HasOne(bc => bc.Category)
.WithMany(c => c.BookCategories)
.HasForeignKey(bc => bc.CategoryId);
}
在我的例子中,我将连接类配置为:
internal class AccountRuleEntityTypeConfiguration : IEntityTypeConfiguration<CompAccountRule>
{
public void Configure(EntityTypeBuilder<AccountRule> builder)
{
builder
.ToTable("AccountRules", "Compliance");
builder
.HasKey(x => new { x.AccountId, x.RuleInstanceId });
builder
.HasOne(x => x.Account)
.WithMany(x => x.AccountRules)
.HasForeignKey(x => x.AccountId);
builder
.HasOne(x => x.RuleInstance)
.WithMany(x => x.AccountRules)
.HasForeignKey(x => x.RuleInstanceId);
}
}
Account
属于默认名称空间,
RuleInstance
属于
Compliance
名称空间,以及这个连接表
AccountRule
也属于
顺从
名称空间,我可以通过语句来配置它
builder.ToTable("AccountRules", "Compliance");
.