EntityFramework Core-没有特定外键的相关实体

问题描述 投票:0回答:1

感谢您抽出时间来研究我的问题。

我正在尝试使用DbContext从数据库中获取一些数据以及相关记录。我已经为我的一种关系提供了此设置的示例-

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<FinancialTransaction>()
                .HasOne<LedgerEntry>(e => e.ledger_entry)
                .WithOne(t => t.financial_transaction)
                .HasForeignKey<LedgerEntry>(e => e.financial_transaction_id);
        }

但是,我还有一个表,该表使用source_idsource_type列的组合来松散引用其他记录。 Source_id是其他记录的主键,source_type是其他记录类型的单数名称(例如“帐户”,“用户”等)。

有人知道与我上面的示例类似的使用EntityFramework进行设置的方法吗?感谢您提供任何建议,如果您需要更多信息,请询问:)

谢谢!

c# entity-framework linq dbcontext ef-model-builder
1个回答
0
投票

您可以使用流利的api定义复合外键:

modelBuilder.Entity<Item>()
            .HasOne(s => s.SubItem)
            .WithMany(i => i.Items)
            .HasForeignKey(s => new {s.source_id, s.source_type});

示例中的解决方案是将一个项目投影到一个新对象,该对象包含要在“ HasForeignKey”表达式中定义为外键的列。

此关系和其他关系在Fluent API - configuring a composite key中详细说明。

© www.soinside.com 2019 - 2024. All rights reserved.