简体   繁体   English

使用 Entity Framework Core 和脚手架处理“动态外键列”

[英]Handle "dynamic Foreign Key columns" with Entity Framework Core and scaffolding

We have some tables in our database-design which include a column named "PK_ID".我们的数据库设计中有一些表,其中包括名为“PK_ID”的列。 This columns are from type "uniqueidentifier" (Guid).此列来自类型“uniqueidentifier”(Guid)。 The uniqueidentifier points to an entity in another table. uniqueidentifier 指向另一个表中的实体。 So it is basically a Foreign Key column.所以它基本上是一个外键列。

The special thing is that there is no constraint on this column.特殊的是,对这一列没有任何限制。 So you can put any uniqueidentifier - value in this column.因此,您可以在此列中放置任何 uniqueidentifier - 值。 We have an additional "Type"-column to determine to which table the uniqueidentifier is pointing to.我们有一个额外的“类型”列来确定 uniqueidentifier 指向哪个表。

This certainly does not correspond to the good rules of database design, but it is necessary in our application context and that is not the point.这当然不符合数据库设计的良好规则,但在我们的应用程序上下文中是必要的,这不是重点。

Our poblem:我们的问题:

When we scaffold our DbContext with dotnet ef dbcontext scaffold EF Core does not recognize the relationships to other tables via the "PK_ID" column.当我们使用dotnet ef dbcontext scaffold构建 DbContext 时,EF Core 无法通过“PK_ID”列识别与其他表的关系。 That is not surprising either.这也不奇怪。

But because this, we cannot use the "Include" and "IncludeThen" methods to build SQL-Join queries.但正因为如此,我们不能使用“Include”和“IncludeThen”方法来构建 SQL-Join 查询。

I hope that was somewhat understandable.我希望这有点可以理解。 How best to deal with this within EntityFramework Core?如何在 EntityFramework Core 中最好地处理这个问题? Is there a way to use methods like "Include" anyway?有没有办法使用“包含”之类的方法?

You can use fluent syntax when querying for this so you can specify how to join您可以在查询时使用流畅的语法,以便您可以指定如何加入

Syntax looks like this: Taken from here: https://entityframework.net/joining )语法如下所示:取自此处: https : //entityframework.net/joining )

var data = context.Authors
    .Join(
        context.Books,
        author => author.AuthorId,
        book => book.Author.AuthorId,
        (author, book) => new
        {
            BookId = book.BookId,
            AuthorName = author.Name,
            BookTitle = book.Title
        }
    ).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM