MVC Link连接数据库增删改查方法的不同写法
时间:2021-07-01 10:21:17
帮助过:26人阅读
System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication5注册验证.Models
{
public class ZhuceBF
{
private mydboDataContext _Context =
new mydboDataContext();
public List<zhuce>
Select()
{
return _Context.zhuce.ToList();
}
public zhuce Selectbyid(
string id)
{
var query = _Context.zhuce.Where(p=>p.ID==
id);
if (query.Count()>
0)
{
return query.First();
}
return null;
}
public void Insert(
string id,
string username,
string userpwd)
{
if (username ==
"" || username ==
" ")
{
}
else
{
zhuce data =
new zhuce();
data.ID =
id;
data.Username =
username;
data.Userpwd =
userpwd;
_Context.zhuce.InsertOnSubmit(data);
_Context.SubmitChanges();
}
}
public void Update(
string id,
string username,
string userpwd)
{
var query = _Context.zhuce.Where(p=>p.ID==
id);
if (query.Count()>
0)
{
zhuce data =
query.First();
data.ID =
id;
data.Username =
username;
data.Userpwd =
userpwd;
}
_Context.SubmitChanges();
}
public void Delete(
string id)
{
var query = _Context.zhuce.Where(p=>p.ID==
id);
if (query.Count()>
0)
{
zhuce data =
query.First();
_Context.zhuce.DeleteOnSubmit(data);
_Context.SubmitChanges();
}
}
//简写方法
public void Insert( zhuce data)
{
_Context.zhuce.InsertOnSubmit(data);
_Context.SubmitChanges();
}
public void Updata(zhuce data)
{
// zhuce sdata = _Context.zhuce.Where(p=>p.ID==data.ID).First();
//上面这一局查询一堆选择第一条
//下面这一局是查询一条,结果一样
zhuce sdata = _Context.zhuce.Single(p=>p.ID ==
data.ID);
sdata.ID =
data.ID;
sdata.Username =
data.Username;
sdata.Userpwd =
data.Userpwd;
}
//删除多条数据
public void Delete(
string name)
{
List<zhuce> list= _Context.zhuce.Where(p => p.Username ==
name).ToList();
_Context.zhuce.DeleteAllOnSubmit(list);
_Context.SubmitChanges();
}
//模糊查询
public List<zhuce> SelectByname(
string name)
{
return _Context.zhuce.Where(r=>
r.Username.Contains(name)).ToList();
}
//表达式查询
public List<zhuce> Selectbyname(
string name)
{
//query相当于一条数据,_Context,zhuce相当于List<zhuce>
var a=
from query1
in _Context.zhuce
where query1.Username.Contains(name)
select query1;
return a.ToList();
}
}
}
MVC Link连接数据库增删改查方法的不同写法
标签: