zoukankan      html  css  js  c++  java
  • ASP.NET Core MVC 中的 Model 模型

    ASP.NET Core MVC 中的 Model

    我们希望最终从 Student 数据库表中查询特定的学生详细信息并显示在网页上,如下所示。

    18 1 18 2

    MVC 中的模型包含一组表示数据的类和管理该数据的逻辑。 因此,为了表示我们想要显示的学生数据,我们使用以下 Student 类。

    public class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string ClassName { get; set; }
        }
    

    ASP.NET Core 中的模型类不必位于 Models 文件夹中,但将它们保存在名为 Models 的文件夹中是一种很好的做法,因为以后更容易找到它们。

    除了表示数据的 Student 类之外,模型还包含管理模型数据的类。 为了管理数据,即检索和保存学生数据,我们将使用以下IStudentRepository服务。 目前,我们只有一个方法**GetStudent()**通过 ID 查询学生。 随着课程的进行,我们将添加创建,更新和删除方法。

     public interface IStudentRepository
        {
            Student GetStudent(int id);
    
        }
    

    以下MockStudentRepository类提供了IStudentRepository接口的实现。 目前,我们正在对MockStudentRepository类中的Student 数据进行硬编码。 在我们即将发布的视频中,我们将为IStudentRepository接口提供另一种实现,该实现将从 SQL Server 数据库中检索数据。

     public class MockStudentRepository : IStudentRepository
        {
            private List<Student> _studentList;
    
            public MockStudentRepository()
            {
                _studentList = new List<Student>()
                {
                new Student() { Id = 1, Name = "张三", ClassName = "一年级", Email = "Tony-zhang@52abp.com" },
                new Student() { Id = 2, Name = "李四", ClassName = "二年级", Email = "lisi@52abp.com" },
                new Student() { Id = 3, Name = "王二麻子", ClassName = "二年级", Email = "wang@52abp.com" },
                };
            }
    
    
            public Student GetStudent(int id)
            {
                return _studentList.FirstOrDefault(a => a.Id == id);
            }
        }
    

    在我们的应用程序中,我们将针对 IStudentRepository 接口进行编程,而不是具体实现 MockStudentRepository。 这种接口抽象化是允许我们使用依赖注入,这反过来也使我们的应用程序灵活且易于单元测试。

    欢迎添加个人微信号:Like若所思。

    欢迎关注我的公众号,不仅为你推荐最新的博文,还有更多惊喜和资源在等着你!一起学习共同进步!

  • 相关阅读:
    安全
    请求
    使用 Fetch
    安全
    script
    PWA
    link(外部资源关系)
    base(根URL)
    缓存
    IndexedDB基本概念
  • 原文地址:https://www.cnblogs.com/cool2feel/p/11455365.html
Copyright © 2011-2022 走看看