Linq 在错误的模式中查询正确的 table

Linq is querying the right table in the wrong schema

我在覆盖 OnModelCreating 函数时将我的默认架构设置为 "WHE":

modelBuilder.HasDefaultSchema("WHE");

我通过 CodeFirst 创建了一个 table Entity Framework:

using System.ComponentModel.DataAnnotations;

namespace Exemptions.Models
{
    public class KillYears
    {
        [Key]
        public int Id { get; set; }
        public string Year { get; set; }
    }
}

这是迁移中的代码:

public override void Up()
    {
        CreateTable(
            "WHE.KillYears",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Year = c.String(),
                })
            .PrimaryKey(t => t.Id);

    }

这是 运行 Update-Database 后数据库中的 table:

Table in the database

这里是对模型的调用:

(from k in model.KillYears
 orderby k.Year descending
 where k.Year != null
 select k).ToList()

...这是我得到的错误:

System.Data.Entity.Core.EntityCommandExecutionException: 'An error occurred while executing the command definition. See the inner exception for details.' Inner Exception SqlException: Invalid object name 'dbo.KillYears'.

我在我的解决方案中搜索了 "dbo.",得到了这个结果:

Find all "dbo.", Find Results 1, Entire Solution, ""
  Matching lines: 0    Matching files: 0    Total files searched: 472

谁能告诉我为什么我的 linq 查询查找错误的架构?自从我接手这个项目以来,我已经在这个项目中创建了 8 或 9 个 table,其中 none 个遇到了这个问题。

有什么建议吗?

编辑:问题是根据@Orwel 提出的问题发现的。构建此应用程序的人最初有两个模型,[appname]Model 和 IdentityModels。 HasDefaultSchema 在一个模型中设置,但在另一个模型中没有设置。我在第二个模型中调用了 HasDefaultSchema,它解决了问题。

您的代码应该可以工作。您确定调用了 HasDefaultSchema 方法吗?如果您的上下文继承自基本上下文,则需要调用 base.OnModelCreating :

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    ...
}