关闭

LINQ TO Entity 增,删,改,查,列表,获得多选框的值实例

1640人阅读 评论(0) 收藏 举报
分类:

效果:

 

一、SQL数据库表结构

tinyint   范围:0 到 255
int       范围:-2,147,483,648 到 2,147,483,647
bit       范围:0 到 1(0表示False 1表示True)
money     范围:小数4位(存储-922337203685477.5808~922337203685477.5807的货币值)
datetime  时间
varchar   可变长度 如:varchar(60) 那表示可以存60个数字,英文
                                         或 可以存30个中文

 

二、创建实体数据模型

 

 

 

 

三、增,删,改,查,列表

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication4.Controllers
{
    /// <summary>
    /// 数据传输对象(Dto)
    /// </summary>
    public class UserDto
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public bool? Sex { get; set; }//?表示数据库中这个字段可以为空
        public int? WorkYear { get; set; }
        public DateTime? WorkTime { get; set; }
        public decimal? Salary { get; set; }
        public string Texts { get; set; }
    }
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //添加
            //UserDto item = new UserDto();
            //item.UserName = "姓名";
            ////item.Sex = true;
            //item.WorkYear = 5;
            //item.WorkTime = DateTime.Now;
            //item.Salary = 7500;
            //AddUser(item);

            //获得一条记录 
            //return View(Fetch(2));

            //修改
            //UserDto item = new UserDto();
            //item.Id = 2;
            //item.UserName = "姓名2";
            //item.Sex = true;
            //item.WorkYear = 5;
            //item.WorkTime = DateTime.Now;
            //item.Salary = 7500;
            //item.Texts = "备注";
            //Update(item);

            //删除
            //Delete(2);

            //列表
            return View(FetchList());
        }

        [HttpPost]//获得多选框的值
        public ActionResult Index(FormCollection fc)
        {
            //获得隐藏域Id的值,并将string数组转换成int数组,获得 2,3
            int[] ArrId = Array.ConvertAll<string, int>(fc["item.Id"].Split(','), delegate(string s) { return int.Parse(s); });            
            //获得多选框的值:只选择了3,提交,获得 "false","3","false"
            string[] ArrSex = fc["item.Sex"].Split(',');
            
            bool[] MyArr = new bool[ArrId.Length];
            for (int i = 0; i < ArrId.Length; i++)
            {
                MyArr[i] = ArrSex.Contains<string>(ArrId[i].ToString());//如果多选框包含隐藏域的值,则返回True   
            }            int count = ArrId.Length;
            using (var ctx = new csEntities())
            {
                int j = 0;
                for (int i = 0; i < count; i++)
                {
                    j = ArrId[i];
                    var mydata = ctx.User.Where(u => u.Id == j).FirstOrDefault();
                    if (mydata != null)
                    {
                        mydata.Sex = MyArr[i];
                        ctx.SaveChanges();
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="item"></param>
        public void AddUser(UserDto item)
        { 
           using(var ctx=new csEntities())
           {
               var newUser = new User { 
                 Id=item.Id,
                 UserName=item.UserName,
                 Sex = item.Sex ?? false,//如果item.Sex为空,那么就是false
                 WorkYear=item.WorkYear??0,
                 WorkTime=item.WorkTime,
                 Salary=item.Salary,
                 Texts=item.Texts
               };
               ctx.AddToUser(newUser);
               ctx.SaveChanges();
           }
        }

        /// <summary>
        /// 获得一条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserDto Fetch(int id)
        {
            using (var ctx = new csEntities())
            {
                var result = (from u in ctx.User
                              where u.Id == id
                              select new UserDto
                              {
                                  Id = u.Id,
                                  UserName = u.UserName,
                                  Sex = u.Sex,
                                  WorkYear=u.WorkYear,
                                  WorkTime=u.WorkTime,
                                  Salary=u.Salary,
                                  Texts=u.Texts
                              }).FirstOrDefault();
                return result;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="item"></param>
        public void Update(UserDto item)
        {
            using (var ctx = new csEntities())
            {
                var data = ctx.User.Where(u => u.Id == item.Id).FirstOrDefault();
                if (data == null)
                    throw new Exception("不存在!");
                data.UserName = item.UserName;
                data.Sex = item.Sex;
                data.WorkYear = item.WorkYear;
                data.WorkTime = item.WorkTime;
                data.Salary = item.Salary;
                data.Texts = item.Texts;
                var count = ctx.SaveChanges();

                if (count == 0)
                    throw new Exception("更新不成功!");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            using (var ctx = new csEntities())
            {
                var data = ctx.User.Where(u => u.Id == id).FirstOrDefault();
                if (data == null)
                    throw new Exception("不存在!");

                ctx.DeleteObject(data);
                ctx.SaveChanges();
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public List<UserDto> FetchList()
        {
            using (var ctx = new csEntities())
            {
                var result = from u in ctx.User
                             select new UserDto
                             {
                                 Id = u.Id,
                                 UserName = u.UserName,
                                 Sex = u.Sex,
                                 WorkYear = u.WorkYear,
                                 WorkTime = u.WorkTime,
                                 Salary = u.Salary,
                                 Texts = u.Texts
                             };
                return result.ToList();
            }
        }

    }


}


四、View视图

@using MvcApplication4.Controllers;@*导入命名空间*@

@*@model List<UserDto>
或是*@
@model IEnumerable<UserDto>

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
@using (Html.BeginForm())
{
    <table border="1" cellspacing="0" cellpadding="0">
        <tr><th>批量修改性别</th><th>姓名</th><th>性别</th><th>工作年限</th><th>工作时间</th><th>工资</th><th>备注</th>
        </tr>
    
    @foreach (var item in Model)
    {
        <tr>
            <td>
            @Html.HiddenFor(model => item.Id)
            @Html.CheckBox("item.Sex", bool.Parse(@item.Sex.ToString()), new { value=@item.Id})
            </td>
            <td>
                @item.UserName
            </td>
            <td>
                @item.Sex
            </td>
            <td>
                @item.WorkYear
            </td>
            <td>
                @String.Format("{0:g}", item.WorkTime)
            </td>
            <td>
                @String.Format("{0:F}", item.Salary)
            </td>
            <td>
                @item.Texts
            </td>
        </tr>
    } 
    </table>
    <input type="submit" value="批量修改性别" />
}
</body>
</html>


 

其它:

 

        /// <summary>
        /// 删除列表
        /// </summary>
        public void DeleteAll()
        {
            using (var ctx = new csEntities())
            {
                foreach (var item in ctx.User)
                {
                    ctx.DeleteObject(item);
                }
                ctx.SaveChanges();
            }
        }

        /// <summary>
        /// 删除一组数据
        /// </summary>
        /// <param name="args"></param>
        public void Delete(string[] args)
        {
            int count = args.Length;

            using (var ctx = new csEntities())
            {
                for (int i = 0; i < count; i++)
                {
                    int id = int.Parse(args[i].ToString());
                    var data = ctx.User.Where(u => u.Id == id).FirstOrDefault();
                    if (data == null)
                        throw new Exception("当前考试计划不存在!");

                    ctx.DeleteObject(data);
                    ctx.SaveChanges();
                }
            }
        }

        /// <summary>
        /// 列表记录数
        /// </summary>
        /// <returns></returns>
        public int ListCount()
        {
            using (var ctx = new csEntities())
            {
                int result = 0;
                result= ctx.User.Where(u => u.Id > 0).Count();
                return result;
            }
        }

        /// <summary>
        /// 将多条记录 添加到 新的对象列表(AddRange)
        /// </summary>
        /// <returns></returns>
        public List<UserDto> FetchListId()
        {
            using (var ctx = new csEntities())
            {
                List<UserDto> plist = new List<UserDto>();

                var result = from u in ctx.User
                             where u.Id == 2
                             select new UserDto { 
                               Id=u.Id
                             };
                plist.AddRange(result);

                var result2 = from u in ctx.User
                             where u.Id == 3
                             select new UserDto
                             {
                                 Id = u.Id
                             };
                plist.AddRange(result2);
                return plist;
            }
        }


 ExecuteStoreCommand

也可以直接执行SQL语句

        private void test()
        {
            using (var ctx = new PersonnelExamEntities())
            {

                ctx.ExecuteStoreCommand("update   dbo.Ex_Examinee set ExamPoint1=96.5");
            }
        }

 

浏览者还查看了下面文章:

Linq to Entity 增,删,改,查 语句

LINQ TO Entity 在数据库发生更改时更新实体数据模型 .edmx 文件

LINQ TO Entity 执行存储过程(不能获得存储过程返回的0或1)

LINQ TO Entity 增,删,改,查,列表,获得多选框的值实例

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:366445次
    • 积分:8375
    • 等级:
    • 排名:第2629名
    • 原创:397篇
    • 转载:55篇
    • 译文:7篇
    • 评论:38条
    最新评论