C# 使用[ForeignKey]访问相关表时,数据库中实际上没有外键,同时使用EF Core

C# 使用[ForeignKey]访问相关表时,数据库中实际上没有外键,同时使用EF Core,c#,foreign-keys,entity-framework-core,C#,Foreign Keys,Entity Framework Core,我正在逆向工程一个我无法更改的第三方数据库。没有外键,但FK关系已由使用它的应用程序强制执行,因此数据正常 我通过scaffoldbcontext运行了表的脚手架,并创建了类。现在由于缺少FKs,我有一个问题。以下是生成类的简化版本: public class Person { public int EmployeeType {get; set; } // other fields } public class EmployeeType { public int Em

我正在逆向工程一个我无法更改的第三方数据库。没有外键,但FK关系已由使用它的应用程序强制执行,因此数据正常

我通过
scaffoldbcontext
运行了表的脚手架,并创建了类。现在由于缺少FKs,我有一个问题。以下是生成类的简化版本:

public class Person
{
    public int EmployeeType {get; set; }
    // other fields
}

public class EmployeeType
{
     public int EmployeeType { get; set; } // this is the key in this table
     // other fields
}
因此,员工有一个分配给它的类型,其中类型存储在查找表中。现在我想查询employee及其类型。所以我试着:

public class Person
{
    public int EmployeeType {get; set; }
    [ForeignKey(nameof(EmployeeType))]
    public EmployeeType EmployeeTypeReference { get; set; }

    // other fields
}

var people = dbContext.Person
        .Include(p => p.EmployeeTypeReference)
        .Where(p => p.EmployeeType != null)
        .Take(10)
        .ToList();
var k = people.Select(c => new { c.EmployeeType, c.EmployeeTypeReference}).ToList();
然后我看到:

即,不检索相关对象

我也试过:

modelBuilder.Entity<Person>(entity =>
{
    entity.HasOne<EmployType>(e => e.EmployeeTypeReference)
                      .WithMany(t => t.People);
}
modelBuilder.Entity(Entity=>
{
entity.HasOne(e=>e.EmployeeTypeReference)
.有很多人(t=>t人);
}
但结果是一样的


我还可以尝试通过
执行任何其他操作来获取相关对象。包括

问题与通常的用户一样。但是,有些人可能也会被此问题所困扰,因此我将详细说明

问题在于
.Include()
。我使用的是来自命名空间
System.Data.Entity
的EF6版本。但我需要来自
Microsoft.EntityFrameworkCore
的EF Core版本


这是由双重运行的EF6带来的(因为依赖关系)和EF Core在同一个项目中。

我会尽最大努力更新数据库并添加FK。如果可能的话,您试图实现的是不安全的。@Siavash我只有对数据库的只读访问权限。无法更改它,因为它被其他应用程序使用。为什么不安全?这应该会起作用。请确保实际查询不会被忽略cludes category(检查已执行的SQL命令,它应该包含
Person
EmployeeType
表的联接)。@IvanStoev检查了已执行的SQL,这两种情况(使用
[ForeignKey]
entity.HasOne(e=>e.EmployeeTypeReference)。with many(t=>t.People);
)返回一个简单的
select*from person
而不包含任何join。但是应该可以。实际映射/使用中一定有错误。您能提供最小的复制吗?(顺便说一句,当前示例未编译事件-
EmployeeType
类不能有
EmployeeType
属性)。请尝试在clean project中使用仅具有PK和关系映射的两个实体进行复制。