2013-07-10 238 views
2

在观看一些实体框架的教程,我看到有创建两个实体之间的关系很多方面。但我很难理解这些线的确切含义。实体框架中的映射?

public virtual Person person { set; get; } 

public virtual IEnumerable<Person> person { set; get; } 

public virtual ICollection<Person> person { set; get; } 

在他们解释的影片之一,当你创建一个属性,它是在同一时间虚拟和ICollection然后这使得延迟加载

什么virtual关键字在这种情况下做的,会是什么如果我们尝试不使用虚拟关键字就会发生

回答

3

EF需要实现类作为虚拟因为这个代理服务器在运行时的一个继承类创建。什么延迟加载引擎做的是重新实现(覆盖)在后台这些属性来达到预期效果。该virtual关键字不正是它:允许其他类重写它的实现。这基本上就是为什么你需要这些属性虚拟,如果你想延迟加载启用和工作。

你会注意到,当延迟加载被启用时,你在运行时得到的实体名称很奇怪,像“Person_Proxy987321654697987465449”。

关于人际关系,只要您创建具有例如1一个实体:在数据库中N的关系,你可以有一个集合,EF自动列出它的关系,所以你可以在你的代码像这样的例子中使用它,假设“人1:N订单”:

var ordersFromSomePerson = person.Orders;

0

为了回答关于为什么虚拟ICollection的使延迟加载在EF的问题,我们需要在该虚拟关键字的定义和含义C#。从MSDN

The virtual keyword is used to modify a method, property, indexer or event declaration, 
and allow it to be overridden in a derived class. For example, this method can be 
overridden by any class that inherits it. 

距离Object Oriented Programming概念的继承机制的一部分。

它往往是的情况下,一个子类需要另一个(扩展)的功能的基类。在这种情况下,虚拟关键字允许程序员倍率(基类的用于该当前实施的默认实现如果需要的话,但所有其他预定义的方法/属性/等仍从基类取!

一个简单的例子是:

// base digit class 
public class Digit 
{ 
    public int N { get; set; } 
    // default output 
    public virtual string Print() 
    { 
     return string.Format("I am base digit: {0}", this.N); 
    } 
} 

public class One : Digit 
{ 
    public One() 
    { 
     this.N = 1; 
    } 
    // i want my own output 
    public override string Print() 
    { 
     return string.Format("{0}", this.N); 
    } 
} 

public class Two : Digit 
{ 
    public Two() 
    { 
     this.N = 2; 
    } 
    // i will use the default output! 
} 

当创建两个对象和打印叫做:

var one = new One(); 
var two = new Two(); 
System.Console.WriteLine(one.Print()); 
System.Console.WriteLine(two.Print()); 

的输出是:

1 
I am base digit: 2 

懒评价在EF中不是来自虚拟关键字直接,但是从覆盖可能性关键字,可以(再次从MSDN上延迟加载):

When using POCO entity types, lazy loading is achieved by creating 
instances of derived proxy types and then overriding virtual 
properties to add the loading hook. 

当预定的方法进行重写,那么程序员可以使延迟加载!