【问题标题】:EntityFramework SqlQuery does not work with custom mapping (DataAnnotation Column)Entity Framework Sql Query 不适用于自定义映射(数据注释列)
【发布时间】:2013-07-17 23:56:15
【问题描述】:

我在 VS 2012 中使用 EF 5.0 (CodeFirst),但无法使用 SqlQuery 进行查询。问题出现在实体的属性名和数据库中列名的映射关系上。

我的实体(模型):

[Table("Teste")]
public class TesteEntity
{
    [Column("Teste_Id")]
    public int Id { get; set; }

    [Required]
    public bool IsAdministrator { get; set; }

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

}

当我运行查询时,我得到一个错误。

罗汀:

List<TesteEntity> list = dataContext.Database.SqlQuery<TesteEntity>("SELECT * FROM Teste").ToList();

错误:

The data reader is incompatible with the specified '....TesteEntity'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name.

数据库中的表结构:

CREATE TABLE [dbo].[Teste](     [Id] [int] IDENTITY(1,1) NOT NULL,
    [IsAdministrator] [bit] NOT NULL,   [Name] [nvarchar](max) COLLATE
Latin1_General_CI_AS NOT NULL,  CONSTRAINT [PK_dbo.Teste] PRIMARY KEY
CLUSTERED  (    [Id] ASC )WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF)
ON [PRIMARY] ) ON [PRIMARY]

显然,当我使用 DataAnnotation [Column ("Teste_Id")] 并重新创建表时,一切正常,但想知道您是否必须使用 DataAnnotation [Column ("Teste_Id")] 进行此查询。

谢谢

【问题讨论】:

    标签: entity-framework ef-code-first data-annotations code-first


    【解决方案1】:

    请把这段代码写成如下:

    [Table("Teste")]
    public class TesteEntity
    {
        [Column("TesteId")]
        [Key]
        public int Id { get; set; }
    
        [Required]
        public bool IsAdministrator { get; set; }
    
        [Required]
        public string Name { get; set; }
    }
    

    我建议您编写代码 EF CF 如何正常工作。对于您的代码,如下所示:

    public class Teste
    {
        public int TesteId{ get; set; }
    
        [Required]
        public bool IsAdministrator { get; set; }
    
        [Required]
        public string Name { get; set; }
    }
    

    【讨论】:

    • 错误仍然存​​在。我使用的原因: [Column ("Teste_Id")] public int Id {get;集;} 是我的实体将继承一个 BaseEntity(具有 Id 属性的抽象类)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多