EntityFramework SqlQuery does not work with custom mapping (DataAnnotation Column)

痞子三分冷 提交于 2019-12-25 11:36:05

问题


I'm using EF 5.0 (CodeFirst) with VS 2012 and am having trouble making a query using SqlQuery. The problem happens in the mapping between the property name of the entity and the name of the column in the database.

My entity (model):

[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; }

}

When I run the query, I get an error.

Rotine:

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

Error:

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.

Table structure in database:

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]

Obviously when I take DataAnnotation [Column ("Teste_Id")] and recreate the table, everything works, but wanted to know if you have to do this query using DataAnnotation [Column ("Teste_Id")].

Thanks


回答1:


Please, write this code as follow:

[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; }
}

I suggest you to write your code How EF CF work fine. For your code it is as follow:

public class Teste
{
    public int TesteId{ get; set; }

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

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


来源:https://stackoverflow.com/questions/17733523/entityframework-sqlquery-does-not-work-with-custom-mapping-dataannotation-colum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!