0

There is the following class:

public class A
{
    [Required]
    public string property { get; set; }      
}

and it's used by another class like:

public class B 
{
    public A prop { get; set; }
    public A prop2 { get; set; }
}

in my scenario, B.prop.property should be required while B.prop2.property should not be [Required].

Is there a way to override prop2.property attribute to be not required? and it also should affect the record recorded in the Database? if not what is the most recommended practice to deal with such issue?

Set
  • 47,577
  • 22
  • 132
  • 150
  • Have a look at [this](https://stackoverflow.com/questions/8903838/is-it-possible-to-override-the-required-attribute-on-a-property-in-a-model) I think it answers your question – UnexpectedSemicolon Apr 02 '18 at 09:54
  • what you described is not an inheritance. I have edited your post accordingly – Set Apr 02 '18 at 10:00

1 Answers1

1

No. There is no way to achieve what you're talking about. You can do so via inheritance. For example:

public class C : A
{
    public new string property { get; set; }
}

Then:

public class B 
{
    public A prop { get; set; }
    public C prop2 { get; set; }
}

In other words, the property must literally be a type where that property is not required. You can't just disable an attribute on a class instance at a whim.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • i ended up making a similar solution, created another class were properties are not required and used it if my field is optional in its entirety. BTW you were amazing in guardian of the galaxy! both the first and the second one, cheers XD << bet you get that a lot – Nawaf Altharwy Apr 03 '18 at 07:16