如何在EF Core中指定多对多关系,其中连接表是架构的一部分



打开https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2流畅的api简单密钥%2简单密钥#加入关系配置他们有以下如何在实体框架核心中指定多对多关系的示例:

modelBuilder.Entity<Post>()
.HasMany(p => p.Tags)
.WithMany(p => p.Posts)
.UsingEntity<Dictionary<string, object>>(
"PostTag",
j => j
.HasOne<Tag>()
.WithMany()
.HasForeignKey("TagId")
.HasConstraintName("FK_PostTag_Tags_TagId")
.OnDelete(DeleteBehavior.Cascade),
j => j
.HasOne<Post>()
.WithMany()
.HasForeignKey("PostId")
.HasConstraintName("FK_PostTag_Posts_PostId")
.OnDelete(DeleteBehavior.ClientCascade));

我如何做同样的事情,但指定PostTag是默认模式之外的模式的一部分?

例如,Test.PostTag[Test].[PostTag]不起作用。当尝试访问资源时,只会导致抛出异常Microsoft.Data.SqlClient.SqlException: 'Invalid object name 'PostTag'.'。因此,当我尝试指定模式名称Test时,它似乎忽略了它。

我所做的就是按照他们在页面上写的去做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也属于Compliance名称空间,我可以通过语句builder.ToTable("AccountRules", "Compliance");进行配置。

最新更新