1

質問は非常に単純で直接的です: EF (5 または 6) にこのコードに従ってデータベースを作成させるにはどうすればよいですか?

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();
}

問題は、EFが作成するデータベースには、人の名前の列が1つしか含まれていないことです...

4

1 に答える 1

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;
       }
    }
}

ご覧のとおり、秘訣は 2 つのプロパティを用意することです。1 つは EF を機能させるため (戻り値の型は Parent)、もう 1 つはインターフェイスを満たすため (戻り値の型は IParent) です。このトリックは、明示的な方法でインターフェイスを実装することで可能になります。

于 2013-06-28T21:03:23.417 に答える