How to make optional REQUIRED for the same attribute on different inherited classes on EF6.
Why the 'required attribute' from one child is required for other child? Why does entity framework merge all data anotations to base classe 'Person' if the base class is non required attributes?
I've used the same classes on MVC to create required fields on cshtml, and it works. The MVC understands only required field from one child and not make any 'wrong merge' with those two child classes.
For example:
//EF Codefirst Class
public class Person
{
[Key]
public int key{get;set;}
[StringLength(500)]
public virtual string name { get; set; }
[StringLength(500)]
public virtual string email{ get; set; }
[StringLength(500)]
public virtual string phone{ get; set; }
[StringLength(500)]
public virtual string address{ get; set; }
[StringLength(500)]
public virtual string manager{ get; set; }
[StringLength(500)]
public virtual string Discriminator{ get; set; }
}
//My Inherited classes
public class Employee : Person
{
[Required]
public override string name{ get; set; }
[Required]
public override string phone{ get; set; }
[Required]
public override string manager{ get; set; }
}
public class Manager: Person
{
[Required]
public override string name{ get; set; }
[Required]
public override string email{ get; set; }
}
//And my sample function 'Add PersonManager'
private void InsertPerson()
{
using (var ctx = new MyDataContext())
{
try
{
var m = new Manager() ;
m.name = "my name" ;
m.email = "my@email.com";
m.address =" something";
ctx.Person.Add(m);
ctx.SaveChanges();
}
catch (Exception ex)
{
// Why, if I try to Add my Person 'Manager', the attribute : phone and manager is REQUIRED?
}
}
}
[Required]
attribute will mark the field as not null in the DB, which means other classes that share that table will also automatically be "required". The database isn't going to support the idea of a conditional null requirement.