C# 强制EF 5或6映射接口成员
问题非常简单和直接:我必须做什么才能使EF5或6根据这段代码创建数据库C# 强制EF 5或6映射接口成员,c#,entity-framework,interface,C#,Entity Framework,Interface,问题非常简单和直接:我必须做什么才能使EF5或6根据这段代码创建数据库 class Program { static void Main(string[] args) { Person parent = new ResponsablePerson(); parent.Name = "Father"; Person child = new Person(); child.Name = "Child";
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创建的数据库只包含一列人名
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。通过以显式方式实现接口,可以实现此技巧。我将使用as和!=null而不是is和cast。这是一个与问题无关的细节。这是一个与答案相关的细节。听起来很公平。这里有一些。如果所提供的示例与宗教编程偏好相比确实存在bug,那么这绝对值得一提。在本例中为和!=根据澄清,null更严格,更不容易出错。