2011-04-08 26 views
0

我已經按照here的描述嘗試了DataAnnotation,但它對我不起作用。帶EF的數據註解

我有一個表結構如下

Table - Category 
    id int (pk not null) 
    CategoryName varchar(100) (null) 

我已經建立了我的EDMX文件和所有。

我創建了類似下面的Category.cs文件。

[MetadataType(typeof(CategoryMetaData))] 
public partial class Category 
{ 
} 

public class CategoryMetaData 
{ 
    [Required(ErrorMessage = "Category Name is required.")] 
    public object CategoryName; 
} 

但我的驗證不起作用。

有什麼我錯過了?

+0

你是如何檢查的? – archil 2011-04-08 07:32:19

+0

我試圖插入填充數據,並插入一個空值。 – Mukesh 2011-04-08 07:46:18

+0

你是如何通過ASP.Net mvc或簡單賦值創建數據的? – archil 2011-04-08 08:17:30

回答

0

UPD Solution here.

驗證之前,您需要手動註冊元數據類

============ ======

我想這個問題與代理類有關,EF爲你的entiti生成ES。您可以在運行時輕鬆檢查:請參閱GetType()。FullName。

如果屬性被標記爲不可繼承,則不會將其應用於繼承類。代理類從實體類派生,所以不可繼承的屬性會丟失。

我想通過手動檢查屬性在WebForms項目中使用DataAnnotations。但無論是

System.ComponentModel.DataAnnotations.Validator.TryValidateObject(entity, new ValidationContext(value, null, null), results, true); 

也不

PropertyInfo[] properties = value.GetType() 
       .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); 

var validationProperties = properties.Select(prop => new 
     { 
      Property = prop, 
      ValidationAttributes = Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true) 
     }).Where(valProp => valProp.ValidationAttributes.Any()); 

不起作用。 我已經試過這些代碼與簡單類與EF無關,並且所有DataAnnotations屬性都被找到並正確檢查。

[MetadataType(typeof(TestValidObject_Metadata))] 
public class TestValidObject 
{ 
    public string IdName { get; set; } 
} 

public class TestValidObject_Metadata 
{ 
    [Required, DisplayName("Id name")] 
    public object IdName { get; set; } 
} 

RequiredAttribute標籤的定義是

[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter, AllowMultiple = false)] 
public class RequiredAttribute : ValidationAttribute 

默認情況下它變得可繼承的屬性。我不知道爲什麼

Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true) 
// true specifies to also search the ancestors of element for custom attributes. 

沒有捕獲它。

歡迎任何想法。

0

CateogryMetaData中的CategoryName應該是一個屬性,並且與原始屬性具有相同的類型。試試這個:

public class CategoryMetaData 
{ 
    [Required(ErrorMessage = "Category Name is required.")] 
    public string CategoryName {get;set;} 
} 
+0

對不起,這沒有奏效。 – Mukesh 2011-04-08 08:06:44

+0

只需仔細檢查,是否與生成的名稱空間位於同一名稱空間中的類別部分類? – 2011-04-08 08:10:23

+0

是的。 edmx和partial類位於相同的目錄和名稱空間中。 – Mukesh 2011-04-08 08:17:11

2

我發現ObjectContext不適用於DataAnnotations。你必須切換到使用DbContext,然後才能正常工作。下載EF 4.x DbContext T4文件並在您的模型上試用。不知道爲什麼這是真的,希望專家會參加。