Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVC3 Buddy Classes issue with validation attributes

0.00/5 (No votes)
27 Aug 2012 1  
MVC3 Buddy Classes issue with validation attributes.

Problem

When you create a Buddy class to add validation attributes to your code-generated models, it doesn't behave as expected.

The generated code:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;

namespace Entities
{
    [DataContract(IsReference = true)]
    [KnownType(typeof(Rental))]
    public partial class Book: IObjectWithChangeTracker, INotifyPropertyChanged
    {
        #region Primitive Properties
    
        [DataMember]
        public int Id
        {
		.
		.
		.
		rest of class 

Here is the Buddy class:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace Entities.Custom
{
    [MetadataType(typeof(BookMeta))]
    public partial class Book
    {
    }

    public class BookMeta
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public double Price { get; set; }
    }
}

Solution

The problem is that the namespaces are different, Entities.Custom in the buddy class and Entities in the generated one.

Just make sure both are equal and everything should be fine.

Points of Interest

Hope this is useful to anyone who encounters this problem, I wasted an hour looking for a solution on the web till I finally had the inspiration to unify the namespaces.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here