从视图表中创建DbQuery

时间:2019-08-08 11:16:41

标签: c# entity-framework-core sql-view ef-core-2.1

我正在尝试从SQL View创建一个ExtendedStudent的DbQuery,该视图是由2个差异表构成的(请参见下面的代码SQL)。

我看了以下帖子:

Entity Framework Core Query TypesEF Core 2.1 Query Types 两者都使用了带有导航属性的模型,然后成功地从Fluent Fluent API中获取了模型。 但是当我也尝试这样做时,出现了诸如“无效的列名'PrefixId1'

我使用的模型是:

public class ExtendedStudent {

    public int IdNumber {get; set;}

    public string FirstName {get; set;}

    public string LastName {get; set;}

    public virtual Prefix Prefix {get; set;}

    public int Score {get; set;}
}

public class Prefix {

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id {get ;set;}

    [required]
    public string Name {get; set;}
}

applicationDbContext.cs文件为:

public class ApplciationDbContext : DbContext{

    DbSet<Prefix> Prefixes {get; set;}

    DbQuery<ExtendedStudent> ExtendedStudents {get ;set;}

    ...

    protected override void OnModelCreating(ModelBuilder builder) {

        builder.Query<ExtendedStudent>.ToView("ExtendedStudent");
        builder.Query<ExtendedStudent>.HasOne<Prefix>().WithMany();
    }
}

最后,我试图像这样获取数据。

var students = applciationDbContext.ExtendedStudents.Include(v => v.Prefix).ToList();

我已经在SQL中创建了ExtendedStudents视图,如下所示:


CREATE VIEW [Organization].[ExtendedStudent] AS
SELECT [TableA].[Student].[FirstName]
        ,[TableA].[Student].[LastName]
        ,[TableA].[Student].[PrefixId]
        ,[TableA].[Student].[IdNumber]
        ,[Evaluation].[Student].[Score]
FROM [TableA].[Student] AS [Students]
INNER JOIN [Evaluation].[Student] ON [Evaluation].[Student].StudentId = [TableA].[Student].[IdNumber]

我尝试将PrefixId属性添加到ExtendedStudent或添加外键,但是没有任何效果。

我说错了

  

“ Microsoft.EntityFrameworkCore.dll中发生了'System.Data.SqlClient.SqlException类型的异常,但未在用户代码中处理:'无效的列名'PrefixId1'。'

1 个答案:

答案 0 :(得分:1)

这里

builder.Query<ExtendedStudent>.HasOne<Prefix>().WithMany();

使用.HasOne<Prefix>(),您要告诉EF Core在每一端创建多对一的关系没有导航属性。

但是导航属性ExtendedStudent.Prefix已经暗示了关系,因此EF Core假定具有默认FK属性和列名PrefixId1 second 关系(因为PrefixId是导航属性所暗示的“其他”关系已经使用了。

要解决此问题,请将导航属性传递给关系配置:

builder.Query<ExtendedStudent>.HasOne(e => e.Prefix).WithMany();