2015-08-27 94 views
0

我有這樣一個模型類:「EntityType沒有定義密鑰」,但我加了[Key],爲什麼?

public class Task 
{ 
    [Key] 
    public int TaskId; 

    public string TaskDescription; 
    public DateTime StartTime; 
    public DateTime FinishTime; 
    public bool isActive; 
} 

和下表中的數據庫:

CREATE TABLE [dbo].[Tasks] 
(
    [TaskId] INT NOT NULL PRIMARY KEY IDENTITY, 
    [TaskDescription] NVARCHAR(max) NOT NULL, 
    [StartTime] DATE NOT NULL, 
    [FinishTime] DATE NOT NULL, 
    [isActive] BIT NOT NULL DEFAULT 1 
) 

編譯後,我得到這個錯誤:

An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code

Additional information:

One or more validation errors were detected during model generation:

Planner.Domain.Concrete.Task: : EntityType 'Task' has no key defined. Define the key for this EntityType. Tasks: EntityType: EntitySet 'Tasks' is based on type 'Task' that has no keys defined.

如何解決一?

+0

我不知道天氣它可能將列DATE更改爲「時間(7)」列類型而無需更改模型的DATETIME字段。如果不可能,相應的c#類型的時間(7)是什麼? – e0x3

回答

8

請添加get和set訪問器。像這樣。

[Key] 
    public int TaskId {get; set;} 
    public string TaskDescription {get; set;} 
    public DateTime StartTime {get; set;} 
    public DateTime FinishTime {get; set;} 
    public bool isActive {get; set;} 
+0

不要忘記'TaskId'的[[Key]' – Rob

+4

@Rob:by ** convention **,一個名爲'Id'或'(tablename)Id'的列將被**自動**用作鍵。由於表/實體是'Task',由於實體框架約定,'TaskId'將自動被用作鍵 –

+1

@Rob,所以''[Key]'應該被這裏的上下文正確地推斷。 – Claies

相關問題