asp.net MVC+ LINQ to Entities简单添加,修改,删除,显示,子查询

  最近一个项目用到asp.net MVC来做,但是数据模型还是采用的是ado.net,在项目完结之时,自己就多看了一下MVC,发现 MVC很多人都在使用EF做为数据模型,自己也就试着写一下,我用EF做数据模型,用linq to Entities来进行操作.下面是自己总结的一些简单操作.

添加操作:

  

//这是我一个EF
NewETrainEntities newEtrain = new NewETrainEntities();

/// <summary>
        /// 添加操作
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateSave()
        {
            //成功失败的标记
            int flag = 1;

           
                try
                {
                    //这是对一个表的model进行定义
                    Etrain_Announcement e_ann = new Etrain_Announcement();

                    e_ann.schoolcode = Request.Form["hidschoolcode"].ToString();
                    e_ann.UserType = Request.Form["selIsapp"].ToString();
                    e_ann.contents = Request.Form["txtContents"].ToString();
                    e_ann.sendTime = DateTime.Now;
                    e_ann.createdate = DateTime.Now;
                    e_ann.modifydate = DateTime.Now;

                    newEtrain.AddToEtrain_Announcement(e_ann);
           
                    //这里要注意,必须要写这个,我一开始以为加上前面的方法add了就已经添加了,这样不会添加,要进行savachanges()才行
                    newEtrain.SaveChanges();
                }
                catch (Exception ex)
                {
                    flag = 0;
                }
           
            


            return Content(flag.ToString());
        }

修改操作:

 /// <summary>
        /// 修改操作
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateSave()
        {
            //成功失败的标记
            int flag = 1;

            try
                {
                    int annid = Convert.ToInt32(Request.Form["hidid"]);

                    var info = from ann in newEtrain.Etrain_Announcement
                               where ann.id == annid
                               select ann;
                    foreach (var item in info)
                    {
                        item.contents = Request.Form["txtContents"];
                    }

                    newEtrain.SaveChanges();
                }
                catch (Exception ex)
                {
                    flag = 0;
                }
                
           
            


            return Content(flag.ToString());
        }

删除操作:

/// <summary>
        /// 删除公告
        /// </summary>
        /// <param name="id">公告ID</param>
        /// <returns></returns>
        public ActionResult DeleteInfo(string id)
        {

            int flag = 1;

            try
            {
                int annid = Convert.ToInt32(id);

                //这里被注掉的部分的是错误的写法
                //var info = from ann in newEtrain.Etrain_Announcement
                           //where ann.id == annid
                           //select ann;
     
             Etrain_Announcement info = newEtrain.Etrain_Announcement.First(p=>p.id==annid);

                newEtrain.DeleteObject(info); 
                newEtrain.SaveChanges(); 
             } 
             catch(Exception ex) 
             { 
                flag = 0; 
             } 
             return Content(flag.ToString()); 
         }

显示操作:

    显示操作这里多说两句,显示操作分为二种情况,一种是对于单表的显示,就是一个表的显示,是比较简单的,请看下面代码:

/// <summary>
        /// 公告列表显示
        /// </summary>
        /// <param name="id">学校标识</param>
        /// <returns></returns>
        public ActionResult adminIndex(string id)
        {
            ViewData["schoolcode"] = id;

            var annInfo = from ann in newEtrain.Etrain_Announcement
                          where ann.schoolcode == id
                          orderby ann.id descending
                          select ann;
          //这里我用了Take(20)这个操作,为得是显示最后20条信息
    return View(annInfo.Take(20));
        }

前台显示也比较简单

 <% foreach (var item in Model)
               { %>
            <tr>
                <td>
                    <% if (Html.Encode(item.contents).Length > 10)
                       { %>
                    <a href="/Announcement/UserView/<%=Html.Encode(item.id) %>">
                        <%= Html.Encode(item.contents).Substring(0, 8)%>...</a>
                    <%}
                       else
                       { %>
                    <a href="/Announcement/UserView/<%=Html.Encode(item.id) %>">
                        <%= Html.Encode(item.contents)%></a>
                    <%} %>
                </td>
                <td>
                    <%= Convert.ToDateTime(Html.Encode(item.sendTime)).ToShortDateString() %>
                    
                    </div>
                </td>
            </tr>
            <% } %>

另一种情况,就是多表查询的时候,这种情况我们一般用得也比较多,就是不是一个独立的表这怎么办呢.其中一种就是表之间有关联,可是如果我没有设置关联怎么办呢.我用的方法比较笨,就是新建一个model.cs文件,把要的字段放进去.然后进行处理,程序如下:

/// <summary>
        /// 页面列表显示
        /// </summary>
        /// <param name="schoolcode">学校标识</param> 
        /// <returns></returns>
        public ActionResult List(string schoolcode)
        {

            

            var smsMould = from sm in newEtrain.ETrain_smsMould
                           join smt in newEtrain.ETrain_smsMouldType on sm.typeID equals smt.typeID 
                           join tea in newEtrain.ETrain_teachers on sm.userID equals tea.teach_id 
                           where sm.schoolCode == schoolcode && sm.userType=="T"
                           orderby sm.id descending
                           //注意这里的myEtrain_smsMould就是我自己写的一个model.cs文件
                           select new myEtrain_smsMould
                           {
                               ID = sm.id,
                               typeName = smt.typeName,
                               mouldContent = sm.mouldContent,
                               userID = sm.userID,
                               teacherName = tea.teach_name,
                               isApproval = sm.isApproval
                           };



            return View(smsMould); 
        }

前台不用,不过有一点要注意的是前台的

<%@ Page Language="C#" MasterPageFile="~/Views/Home/Main.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<_3GEtrain.Models.myEtrain_smsMould>>" %>
 Inherits="System.Web.Mvc.ViewPage<IEnumerable<_3GEtrain.Models.myEtrain_smsMould>>//这里的名字一定是你定义的类别

这个显示中还有一个join的方法,是用的多表链接,这里有一个问题 就是 linq to Entities中没有左连接,而且3.5版的还没有DefaultIfEmpty().哪位朋友有好的方法,告诉我一下.


下面是一个子查询的例子.也很简单,不多说,上代码

/// <summary>
        /// 班级订购人数统计
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ClassRegNum(string id)
        {
            var info = from sc in newEtrain.ETrain_school_class
                       join grade in newEtrain.ETrain_grade on sc.grade_id equals grade.grade_id
                       where sc.schoolcode == id
                       orderby sc.grade_id, sc.class_id
                       select new ClassRegNum
                       {
                           grade_class = grade.grade_name + sc.class_Alias,
                           StudentNum = (from stu in newEtrain.ETrain_stu_class where stu.class_id == sc.class_id && stu.schoolcode == id && stu.grade_id == sc.grade_id select stu).Count(),
                           RegSum = (from stuc in newEtrain.ETrain_stu_class
                                     join k in newEtrain.ETrain_stu_kindred on stuc.stu_id equals k.stu_id
                                     join reg in newEtrain.reg_sms_user on k.parent_mobile equals reg.mobile_number
                                     where stuc.schoolcode == id && stuc.grade_id == sc.grade_id && stuc.class_id == sc.class_id && reg.reg_type == 1
                                     select stuc).Count()
                       };

            return View(info);
        }

这个代码,虽然有一点乱,但是仔细看,还是很简单的.呵.........


你可能感兴趣的:(JOIN,mvc,exception,equals,asp.net,LINQ)