zoukankan      html  css  js  c++  java
  • EF中連表查詢的應用方式

    1.首先我們想讓列表頁顯示兩個表的共同數據

    這裡有兩張表

       public class mytype
        {
            public int mytypeID { get; set; }
            public string mytypeName { get; set; }
        }

      public class Author
        {
            public int AuthorID { get; set; }
            public string AuthorName { get; set; }
        }

    2.然後新建立一個新的文件夾,然後添加一個類

      public class all
        {
            public int id { get; set; }

            public string type { get; set; }

            public string other { get; set; }

        }

    3.  public class mytryController : Controller
        {
            //
            // GET: /mytry/
            AllContext db = new AllContext();

            public ActionResult Index() //在這裡我們獲取到了類all中的數據
            {
                var a = from i in db.Mytype
                        from j in db.Author
                        where i.mytypeID == j.AuthorID
                        select new all{ id=i.mytypeID, type=i.mytypeName, other=j.AuthorName };
                return View(a);
            }
        }

    4.然後再對應的視圖頁面

    @model IEnumerable<MvcApplication12.viewModel.all>

    然後再下面下出,這樣你所需要的數據就出來了

      @foreach (var item in Model)
        {
         @item.id
         @item.type
         @item.other
         }

    現在還有一個類似的方法

    首先添加一個all類

    namespace MvcApplication12.viewModel
    {
        public class all
        {
            public IEnumerable<Author> author { get; set; }
            public IEnumerable<mytype> mytype { get; set; }
        }
    }

    在控制器中

       public class mytryController : Controller
        {
            //
            // GET: /mytry/
            AllContext db = new AllContext();
            viewModel.all al = new viewModel.all();
            
            public ActionResult Index() //在這裡我們獲取到了類all中的數據
            {
                var a = from i in db.Mytype
                        from j in db.Author
                        where i.mytypeID == j.AuthorID
                        select new myClass{Id=i.mytypeID,Type=i.mytypeName,Name=j.AuthorName};

             
                return View(a);
            }
        }

        public class myClass
        {
            public int Id { get; set; }
            public string Type { get; set; }
            public string Name { get; set; }
        }

    然後在視圖頁面

    @model IEnumerable<MvcApplication12.Controllers.myClass>

        @foreach (var item in Model)
        {
        @item.Id
        @item.Name
        @item.Type
         }

    這樣也是可以的。

    ok

  • 相关阅读:
    pandas高效实现条件逻辑
    Python教程:文件、异常处理和其他
    最终初学者指南,以数据科学用例赢得分类黑客马拉松
    用Nvidia Jetson Nano 2GB和Python构建一个价值60美元的人脸识别系统
    一幅图像能顶16x16字!——用于大规模图像缩放识别的变压器(对ICLR 2021年论文的简要回顾)
    接缝雕刻算法:一种看似不可能的图像大小调整方法
    apache与nginx的优缺点的比较
    php5与php7的区别
    git基本的命令大全
    redis和membercache的区别
  • 原文地址:https://www.cnblogs.com/sdya/p/3973246.html
Copyright © 2011-2022 走看看