1

The question is very simple and direct: What do I have to do to make EF (5 or 6) create the database accordingly to this code

class Program
{
    static void Main(string[] args)
    {
        Person parent = new ResponsablePerson();
        parent.Name = "Father";

        Person child = new Person();
        child.Name = "Child";
        child.Parent = parent;

        using (PersonContext pc = new PersonContext())
        {
            pc.Persons.Add(parent);
            pc.Persons.Add(child);
            pc.SaveChanges();
        }
        Console.ReadKey();
    }
}

public class Person : IPerson
{
    [Key]
    public string Name { get; set; }
    public IPerson Parent { get; set; }

    public virtual void Work()
    {
        Console.WriteLine("How much are you payng me? Ok I'll do it!");
    }
}

public class ResponsablePerson : Person
{
    public override void Work()
    {
        Console.WriteLine("Right Now!");
    }
}

public class NotResponsablePerson : Person
{
    public override void Work()
    {
        Console.WriteLine("Oh HELL NO!");
    }
}

public interface IPerson
{
    string Name { get; set; }
    IPerson Parent { get; set; }

    void Work();
}

The thing is that the database EF creates contains only 1 column for the name of the person...

Leonardo
  • 10,737
  • 10
  • 62
  • 155

1 Answers1

0
public class Person : IPerson 
{
    public virtual Parent Parent { get; set; }

    IParent IPerson.Parent
    {
       get { return this.Parent; }
       set
       {
          if (!(value is Parent)) throw new ArgumentException();
          this.Parent = (Parent)value;
       }
    }
}

As you can see, the trick is to have two properties, one to make EF work (returning type is Parent) and the other to satisfy the interface (returning type is IParent). The trick is possible by implementing the interface in an explicit way.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106