How to add Alternate Key constraint to Entity Property


  • I know I can define an entity property key in the metadata.cs file like this:

    public int Id
    Now I have a name property and it's unique. this is known as alternate key in database.
    i don't know how to add the unique constraint to the name property of entity.
    I have tried to use a customvalidator metadata as follows:
    [StringLength(8,ErrorMessage="Length can't be more than 8.")]
    public string Name { get; set; }

     the validator class  in Validator.shared.cs:

    public static class DepartmentTypeValidator
            public const string NamValidator = "IsNameValid";
            public static ValidationResult IsNameValid(string name, ValidationContext context)
                BusinessWorkEntities entities = new BusinessWorkEntities();
                return entities.DepartmentType.Any(d => d.Name == "name") ?
                    new ValidationResult("Name exists.", new string[] { "Name" }):ValidationResult.Success : ;

     the shared.cs file will be copy to client to force validate properties, but client don't know the entitycontext.

    so there will be a error.

    Is there a metadata attribute that can be used to indicate an alternate key or a method can used to validate an alternate key

    (a property or a group of properties)

    Sunday, April 29, 2012 3:54 AM


All replies