2013-09-30 50 views
1

我有一個定製的Date類,它包裝DateTime對象以僅公開日期部分。帶非POCO類的EF

我試圖將其納入一個實體,但得到的異常:

error 3004: Problem in mapping fragments starting at line 6:No 
mapping specified for properties Goal.Date in Set Goal.\r\nAn Entity with Key 
(PK) will not round-trip when:\r\n Entity is type [EFCodeFirstSandbox.Goal] 

是怎麼回事?我如何讓自定義課程在EF世界中發揮出色?

這裏的風俗Date類的簡單化下來的版本:使用Date

public class Date 
{ 
    private DateTime value; 
    public Date(DateTime date) 
    { 
     this.value = date.Date; 
    } 
    public static implicit operator Date(DateTime date) 
    { 
     return new Date(date); 
    } 
    public static implicit operator DateTime(Date date) 
    { 
     return date.value; 
    } 
} 

實體類:

public class Goal 
{ 
    [Key] 
    public Guid Id { get; set; } 
    public Date Date { get; set; } 
    public int Amount { get; set; } 
} 

編輯:這Date類只是用於說明目的。我很想知道如何映射自定義非POCO類,而不是如何在SQL中表示日期。 :)

回答

1

事實上EF說:「我不知道如何與Date類」。由於Date屬性是對另一個類的引用,因此EF想要定義此類的映射,並且要定義GoalDate之間的關聯。他們都不是。

我將映射一個完整DateTime屬性數據庫列,並創建一個返回此DateTime屬性的日期部分計算性能。

例如(如@Excommunicated指出):

partial class Goal 
{ 
    [System.ComponentModel.DataAnnotations.Schema.NotMapped] 
    public DateTime DateTrunc 
    { 
     get { return this.Date.Date; } 
    }   
} 
+0

你能指點我什麼能告訴我更多關於創建計算屬性的內容嗎? – FOO

+1

在您的目標類中創建另一個屬性,返回您的日期類型並僅從DateTime屬性計算它。使用[NotMapped]屬性標記日期屬性,或者將其標記爲映射,無論您聲明映射,鍵和關係等。 – Excommunicated

+0

@Chris請參閱我的編輯。 –

0

正如@GertArnold說,保持列類型爲DateTime。添加一個部分類定義來公開您需要的任何附加屬性。

0

你得到的錯誤意味着,EF嘗試resolvve的Date類型的表(像你做任何其他類),並沒有用於Date類型沒有主鍵。
您應該使用DateTime並使用[DataType(DataType.Date)]裝飾房產。

1

我不相信你可以做你以後的事情。您需要使用類型實體框架知道如何映射。你需要做的是使用DateTime並使用只讀或未映射的屬性來公開你的自定義類型。

public class Goal 
{ 
    [Key] 
    public Guid Id { get; set; } 
    public DateTime Date { get; set; } 
    public int Amount { get; set; } 

    // Read only field not mapped 
    public Date CustomDate { get { return this.Date; }} 

    // OR... specificallly ignored property that enables date setting 

    [NotMapped] // In System.ComponentModel.DataAnnotations.Schema namespace 
    public Date CustomDate { 
           get { 
            return this.Date; 
           } 
           set { 
            this.Date = value; 
           } 
          }   
}