我有以下课程:
public class Delivery
{
// Primary key, and one-to-many relation with Customer
public int DeliveryID { get; set; }
public virtual int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
// Properties
string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么他们的客户信息是用虚拟编码的.这是什么意思?
从评论来看,您正在学习实体框架?
虚拟这里意味着你正在尝试使用延迟加载 - 当客户可以自动加载像Customer这样的相关项目时
例如,当使用下面定义的Princess实体类时,将在第一次访问Unicorns导航属性时加载相关的独角兽:
public class Princess
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Unicorn> Unicorns { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
猜猜你用的是EF。
当您创建NavigationProperty虚拟时,EF 会动态创建一个派生类。
该类实现的功能允许延迟加载和其他任务,例如维护 EF 为您执行的关系。
只是为了了解您的示例类动态地变成这样:
public class DynamicEFDelivery : Delivery
{
public override Customer Customer
{
get
{
return // go to the DB and actually get the customer
}
set
{
// attach the given customer to the current entity within the current context
// afterwards set the Property value
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在调试时轻松看到这一点,EF 类的实际实例类型具有非常奇怪的名称,因为它们是动态生成的。