Mukesh
Mukesh

Reputation: 807

Dataannotation with EF

I have tried DataAnnotation as described here, but it does not work for me.

I have a table with the following structure

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

I already created my edmx file and all.

I have created the Category.cs file also like below.

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

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

But my validations are not working.

Is there anything I've missed?

Upvotes: 0

Views: 626

Answers (3)

Paul Berglund
Paul Berglund

Reputation: 91

I have found that ObjectContext does not work with DataAnnotations. You have to switch to using DbContext, then it works. Download the EF 4.x DbContext T4 file and try it on your model. Not sure why this is true, was hoping an expert would chime in.

Upvotes: 2

Mikhail Fiadosenka
Mikhail Fiadosenka

Reputation: 321

UPD Solution here.

Before validating, you need to manually register the metadata class

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

I suppose this problem is related to proxy classes, which EF generates for your entities. You can check this easily in runtime: just see GetType().FullName.

If attribute is marked as non-inheritable, it won't be applied in inherited class. And proxy classes derive from entity classes, so non-inheritable attributes are lost.

I'm trying to use DataAnnotations in WebForms project by checking attributes by hand. But neither

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

nor

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

doesn't work. I've tried these code with simple class not related to EF, and all DataAnnotations attributes were found and checked correctly.

[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's definition is

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

and by default it becomes inheritable attribute. And I don't know why

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

doesn't catch it.

Any ideas are welcome.

Upvotes: 0

Quang Vo
Quang Vo

Reputation: 492

CategoryName in CateogryMetaData should be a property and has the same type as the original property. Try this:

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

Upvotes: 0

Related Questions