c# - 为什么我需要在 C# 类中使用虚拟修饰符?

标签 c#

我有以下类(class):

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

有人能解释一下为什么他们的客户信息是用虚拟编码的吗?什么意思?

最佳答案

看评论,你在学Entity Framework?

这里的虚拟意味着您正在尝试使用延迟加载 - 当相关项目(如 Customer)可以由 EF 自动加载时

http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

例如,当使用下面定义的 Princess 实体类时,相关的 unicorn 将在第一次访问 Unicorns 导航属性时加载:

public class Princess 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Unicorn> Unicorns { get; set; } 
}

关于c# - 为什么我需要在 C# 类中使用虚拟修饰符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9750425/

相关文章:

c# - 使用窗口窗体中的按钮从列表框中删除所选项目

c# - 将 Excel 互操作的 Range.Value2 转换为字符串

c# - ASP.NET MVC 6 文件夹授权

c# - 如何有效裁剪 *indexed* 位图并获得 *indexed* 结果?

c# - ASP.NET MVC,用于将验证消息从服务层验证传输到 View 模型的解决方案

c# - 如何对 ASP.NET Core Controller 或模型对象进行单元测试?

c# - 如何设置依赖属性值?

c# - 如何调整画笔纵横比

c# - Unity - Android,C# - C++ 内存泄漏

c# - 为什么不允许在派生接口(interface)上显式实现基接口(interface)的方法?