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

如您所见,诀窍是拥有两个属性,一个使 EF 工作(返回类型为 Parent),另一个满足接口(返回类型为 IParent)。这个技巧可以通过以显式方式实现接口来实现。

于 2013-06-28T21:03:23.417 回答