【发布时间】:2019-12-16 02:09:51
【问题描述】:
我正在尝试从由 2 个不同表构造的 SQL 视图创建 ExtendedStudent 的 DbQuery(参见下面的代码 SQL)。
我看过以下帖子:
Entity Framework Core Query Types 和EF 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]
我尝试向 ExtendedStudent 添加 PrefixId 属性,或者添加外键,但没有任何效果。
我收到一个错误提示
“Microsoft.EntityFrameworkCore.dll 中出现了‘System.Data.SqlClient.SqlException’类型的异常,但未在用户代码中处理:‘无效的列名‘PrefixId1’。”
【问题讨论】:
标签: c# entity-framework-core sql-view ef-core-2.1