EntityFramework SqlQuery不适用于自定义映射(DataAnnotation Column) [英] EntityFramework SqlQuery does not work with custom mapping (DataAnnotation Column)

查看:201
本文介绍了EntityFramework SqlQuery不适用于自定义映射(DataAnnotation Column)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VS 2012中使用EF 5.0(CodeFirst),并且无法使用SqlQuery进行查询。问题发生在实体的属性名称和数据库中列的名称之间的映射。

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.

我的实体(型号):

[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();

错误:

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)]进行查询。

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")].

谢谢

推荐答案

请写下如下代码:

[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工作正常。对于您的代码,如下所示:

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

这篇关于EntityFramework SqlQuery不适用于自定义映射(DataAnnotation Column)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆