nilesh1foru
nilesh1foru

Reputation: 57

How can I override the properties in partial class?

I am developing a MVC application, I have used EF 4.0 while developing it. I have created the classes from the model. Now, I want to add more class for each class made by MVC.

ex. In below code, I get the class Location. Now, I want to create one more class(Partial class) How can I override properties in partial class ?

How to do that ?

namespace Entities
{
   public partial class Location
   {               
       public int Id { get; set; }

       public string Name { get; set; }
       public string Remark { get; set; }      
       public string State { get; set; }       
       public string Region { get; set; }
       public string PinCode { get; set; }

       public virtual ICollection<Comment> Comments { get; set; }
   }    
}

Upvotes: 0

Views: 6376

Answers (2)

undefined
undefined

Reputation: 34238

You can do attribute decoration in a partial class with an interface

If you have generated the following class (via whatever custom tool)

public partial class Location
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Remark { get; set; }
    public string State { get; set; }
    public string Region { get; set; }
    public string PinCode { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

You can add annotations to properties in the generated class (without modifying the generated file) by creating a new interface and a new partial class as below

    public interface ILocation
    {
        [StringLength(50, ErrorMessage = "Region can accept maximum 50 characters.")]
        string Region { get; set; }
    }

    public partial class Location :ILocation
    {
    }

Upvotes: 14

Sergei Rogovtcev
Sergei Rogovtcev

Reputation: 5832

If all you need is validation, you can use so-called metadata types.

Detailed tutorial is here.

Upvotes: 0

Related Questions