Click here to Skip to main content
15,881,938 members
Articles / Programming Languages / C#
Tip/Trick

MVC3 Buddy Classes issue with validation attributes

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
27 Aug 2012CPOL 9K   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:

C#
//------------------------------------------------------------------------------
// <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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Egypt Egypt
Enthusiastic programmer/researcher, passionate to learn new technologies, interested in problem solving, data structures, algorithms, AI, machine learning and nlp.

Amateur guitarist/ keyboardist, squash player.

Comments and Discussions

 
-- There are no messages in this forum --