Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop the [Required] annotation from being inherited on overridden fields?

I've got a model for a phone number notification (users get notified of emergencies via phone numbers that they associate with their account, and they can set what order these are called in). Most of the time, the phone number part of the model is required, but there's a special case during creation of a new user where we don't want to force it.

I made a very simple child object UserCreationPhoneNotificationModel that inherits from the above described UserPhoneNotificationModel. There's a couple other small changes, but the relevant one here is overriding the PhoneNumber field so that it's no longer required.

In the parent model it's

[Required]
public virtual string PhoneNumber { get; set; }

And in the child model it's just

public override string PhoneNumber { get; set; }

I figured this would do the trick, but apparently not. I thought the issue would be that RequiredAttribute would have Inherited = true on it, but it doesn't so I'm not entirely sure why it's being inherited into the subclass.

I did double check to make sure, and removing Required from the field in the parent also made the field in the subclass not required, so it's definitely some kind of inheritance thing.

like image 920
Kyle S Avatar asked Apr 11 '13 19:04

Kyle S


2 Answers

It can be done by Hiding the existing Property by a new property of the same name. So, if the property is like this in the parent class:

[Required]
public virtual string PhoneNumber { get; set; }

You can define the new property in the child class like this:

public new string PhoneNumber { get; set; }

This will hide the PhoneNumber Property along with its Attributes in the child class. Now you can use any other attributes with it. For example, you can add [PhoneNumber] attribute to the property in the child class.

like image 153
Anup Sharma Avatar answered Sep 28 '22 05:09

Anup Sharma


Using inheritance to share behaviour when the relationship you're modelling doesn't fit can be problematic. You do not typically get any benefit from using inheritance to share behaviour between ViewModels, while you can (and, as in your case, do) encounter problems.

Your best bet is to use a different model class for each use-case. If you genuinely need to share behaviour between ViewModels, you can do so with composition.

like image 37
Iain Galloway Avatar answered Sep 28 '22 05:09

Iain Galloway