强制EF 5或6映射接口成员

时间:2013-06-28 20:29:33

标签: c# entity-framework interface

问题非常简单直接:我需要做些什么才能使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列...

1 个答案:

答案 0 :(得分: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)。通过以明确的方式实现接口,可以实现这一诀窍。