c# - 为什么在使用 Entity Framework 6.x 通过 SqlQuery 从 View 中获取数据时不使用我的 ColumnAttribute?

标签 c# .net sql-server entity-framework

我正在努力使用 DbContext 和下面的实体从 SQL View 中正确获取数据:

public class StagingDbContext : ApplicationDbContext
{
    private const string AssignmentQuery =
        @"SELECT DISTINCT " +
        @"[Region], " +
        @"[Technician], " +
        @"[Email], " + 
        @"[On Call Group], " + 
        @"[Manager], " + 
        @"[Manager Email] " +
        @"FROM [Staging].[dbo].[Assignment] " +
        @"WHERE " + 
        @"[Technician] IS NOT NULL AND " +
        @"[Technician] NOT LIKE 'DECOMMISSIONED' " +
        @"AND [Technician] NOT LIKE 'N/A' " +
        @"AND [Technician] NOT LIKE '4242NAH%' " +
        @"AND [Region] IS not Null " +
        @"AND [On Call Group] NOT LIKE 'N/A' " +
        @"AND [On Call Group] NOT LIKE 'Decommisioned'";

    public IEnumerable<Assignment> Assignments => Database.SqlQuery<Assignment>(AssignmentQuery);

    public StagingDbContext ()
        : base(nameof(StagingDbContext ))
    {
    }
}

[Table("Assignment")]
public class Assignment
{
    [Column("Region")]
    public string Region { get; set; }

    [Column("SiteID")]
    public string SiteId { get; set; }

    [Column("Technician")]
    public string Technician { get; set; }

    [Column("Email")]
    public string Email { get; set; }

    [Column("On Call Group")]
    public string OnCallGroup { get; set; }

    [Column("Manager Email")]
    public string ManagerEmail { get; set; }
}

当涉及到与查询中提供的属性名称不完全匹配的属性名称时,我的问题就出现了,我认为 ColumnAttribute 已被考虑在内,但显然事实并非如此。

我目前的解决方法是基本上重命名我的 SQL 查询中的列([Column Name] AS ColumnName 以使它们直接匹配我的实体的属性名称(例如删除空格字符)但我发现它有点尴尬专门为该特定目的重写查询。

有什么办法可以强制 SqlQuery 使用我的 ColumnAttribute 提供的名称而不是属性?

[编辑] 它或多或少已经在其他地方得到了回答:

最佳答案

My current workaround is to basically rename columns in my SQL query ([Column Name] AS ColumnName in order to make them match directly to the property names of my entity (e.g. removing white space characters) but I found it a bit awkward to rewrite the Query exclusively for that particular purpose.

是的,这确实很尴尬,但据我所知,这是唯一的方法。

您正在寻找的功能(使用映射配置将 SqlQuery/存储过程结果映射到实体)在 EF 6.x 中不存在,并且 will not be implemented

关于c# - 为什么在使用 Entity Framework 6.x 通过 SqlQuery 从 View 中获取数据时不使用我的 ColumnAttribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340363/

相关文章:

c# - 并发字典多次写入

c# - 按字母顺序将值插入 .txt 文件

asp.net - 使用 Owin 时出现 Access-Control-Allow-Origin 错误

sql-server - 更改 SQL Server 中的当前数据库路径

c# - 在 Run 中指定相对 FontSize

c# - 为什么我的 ID 会随着互联网连接而改变?

c# - 重写属性上的 .net XmlSerializer

.net - 如何为 web/app.config 架构创建扩展 xsd?

c# - 如何使用 EF Code First 有效地初始化大型种子?

sql-server - SQL Server 全文搜索 - 是否可以在单词中间进行搜索?