0

我在VS 2012中使用EF 5.0(CodeFirst),並且無法使用SqlQuery進行查詢。問題發生在實體的屬性名稱和數據庫中列的名稱之間的映射中。EntityFramework SqlQuery不適用於自定義映射(DataAnnotation列)

我的實體(模型):

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

} 

當我運行查詢,我得到一個錯誤。

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 [柱( 「Teste_Id」)],並重新創建表,一切正常,但想知道是否必須使用DataAnnotation [Column(「Teste_Id」) ]。

感謝

回答

0

請,寫這樣的代碼如下:

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

錯誤仍然存​​在。我正在使用的原因: [Column(「Teste_Id」)] public int Id {get;設置;} 是我的實體將繼承BaseEntity(具有Id屬性的抽象類)。 –

+0

謝謝你的信息 –