asp.net mvc 三层加EF两表联查

首先打开vs软件
新建项目
创建web中的mvc项目
再右击解决方案创建类库项目
分别创建DAL层和BLL层再把DAL层和BLL层的类重命名
在mvc项目中的Models文件夹创建model类
在DAL创建ADO.NET实体数据模型后把DAL层中App.Config文件中的链接字符串复制到mvc项目的Web.config文件中

ADO.NET实体数据模型


DAL层中的类开始打代码

 /// <summary>
        /// 两表联查
        /// </summary>
        /// <returns></returns>
        public static List<dynamic> biao()
        {
            using (KaoshiEntities db = new KaoshiEntities())
            {
                var sql = from s in db.Student
                          join c in db.Bang on s.ID equals c.Bid
                          select new
                          {
                              s.Name,
                              s.passwork,
                              c.BName
                          };
                List<dynamic> li = new List<dynamic>();
                foreach (var item in sql.ToList())
                {
                    dynamic d = new ExpandoObject();
                    d.name = item.Name;
                    d.pwd = item.passwork;
                    d.Bname = item.BName;
                    li.Add(d);
                }
                return li;
            }
        }

BLL层

 /// <summary>
        /// 两表联查
        /// </summary>
        /// <returns></returns>
        public static List<dynamic> biao()
        {
            try
            {
                return KaoshiDAL.kaoshidal.biao();
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }

mvc项目中的Models文件夹的model类

 /// <summary>
        /// 两表联查
        /// </summary>
        /// <returns></returns>
        public static List<dynamic> biao()
        {
            try
            {
                return KaoshiBLL.kaoshibll.biao();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

在mvc项目中的Controllers文件夹创建Home控制器

 /// <summary>
        /// 两表联查
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            List<dynamic> li =kaoshiModel.biao();
            return View(li);
        }

Index视图

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<table style="width: 40%;" border="1">
    <tr>
        <th>姓名</th>
        <th>密码</th>
        <th>班级</th>
    </tr>
    @foreach (var item in Model)
    {
    <tr>
        <td>@item.name</td>
        <td>@item.pwd</td>
        <td>@item.Bname</td>
    </tr>
      }
</table>

 


posted @ 2019-03-23 10:18  勿语轻尘  阅读(1567)  评论(0编辑  收藏  举报