博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

linqEntity直接修改指定字段,不需查询

Posted on 2011-10-13 10:19  itcfj  阅读(691)  评论(0编辑  收藏  举报
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using System.Data;
using System.Data.Objects;
public partial class _Default : System.Web.UI.Page
{

testdbEntities db = new testdbEntities();
protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{

Response.Write(db.DefaultContainerName + "<br/>");
object outModel;
if (db.TryGetObjectByKey(new EntityKey("testdbEntities.tb1", "id", 2), out outModel))
{
tb1 tempModel = outModel as tb1;
Response.Write(tempModel.EntityState.ToString());
Response.Write(tempModel.userName);
}
}
protected void Button2_Click(object sender, EventArgs e)
{


tb1 addModel = new tb1();
addModel.id = 45;
addModel.passWord = "22222";
addModel.userName = "UserName";
Response.Write(addModel.EntityState.ToString() + "<br/>");
db.AddObject("tb1", addModel);
Response.Write(addModel.EntityState.ToString() + "<br/>");
db.SaveChanges();
Response.Write(addModel.EntityState.ToString() + "<br/>");


}
protected void Button3_Click(object sender, EventArgs e)
{
var tbModel = db.tb1.Where(P => P.userName == "UserName");
Response.Write((tbModel as ObjectQuery).ToTraceString());

}

protected void Button4_Click(object sender, EventArgs e)
{
/*
* ApplyPropertyChanges调用时,要求对应的[实体]在内存中,Attach不要求
ApplyPropertyChanges调用后,集合内的实体状态会标记为EntityState.Modified
Attach调用后不会修改合内的实体状态,如要SaveChanges(),要手动标记EntityState.Modified
ApplyPropertyChanges是用[外部实体]全覆盖Context集合中的[实体],
Attach方式,通过SetModifiedProperty()方法,可在调用SaveChanges()时,只修改只定有字段值
使用ApplyPropertyChanges,可以使用不在集合中的实体覆盖到集合中主键对应用实体上,如果内存中没有主键对应的记录,
* 会报错:“ObjectStateManager 不包含具有对“XXX”类型的对象的引用的 ObjectStateEntry。”该方法还有一个特点就是,
* 拿内存中的对象(新对象)和context中的对象(旧对象)对比,自动生成对应字段修改的Update语句,如果内存中的对象与context中的对象完全相等(每个字段的值都相等),将不生成响应的Update
*/
#region

tb1 tbTemp = db.tb1.FirstOrDefault<tb1>(P => P.id == 45);
tbTemp.userName = "ApplyCurrent";
db.ApplyCurrentValues<tb1>("tb1", tbTemp);
db.SaveChanges();
/*
先查询
SELECT TOP (1)
[Extent1].[id] AS [id],
[Extent1].[userName] AS [userName],
[Extent1].[passWord] AS [passWord],
[Extent1].[a] AS [a]
FROM [dbo].[tb1] AS [Extent1]
WHERE 45 = [Extent1].[id]
更新语句
exec sp_executesql N'update [dbo].[tb1]
set [userName] = @0
where ([id] = @1)
',N'@0 varchar(50),@1 int',@0='ApplyCurrent',@1=45
*/
#endregion

#region
tb1 UpdatgModel = new tb1();
UpdatgModel.id = 45;
UpdatgModel.passWord = "我爱你";

// UpdatgModel.userName = "122";
// db.ApplyCurrentValues<tb1>("tb1", UpdatgModel);
db.AttachTo("tb1", UpdatgModel);
db.ObjectStateManager.ChangeObjectState(UpdatgModel, EntityState.Modified);
db.SaveChanges();
/* 生存的SQL语句
exec sp_executesql N'update [dbo].[tb1]
set [userName] = null, [passWord] = @0, [a] = null
where ([id] = @1)
',N'@0 varchar(50),@1 int',@0='我爱你',@1=45
*/
#endregion

//using (BlogDbContext context = new BlogDbContext())
//{
// var blog = new Blog() { BlogID = 0, LastModified = DateTime.Now };
// context.BlogConfigs.Attach(blog);
// var stateEntry = ((IObjectContextAdapter)context).ObjectContext.
// ObjectStateManager.GetObjectStateEntry(blog);
// stateEntry.SetModifiedProperty("LastUpdated");
// context.SaveChanges();
//}

//using (testdbEntities db=new testdbEntities ())
//{
// var tbTemp = new tb1 { id = 45, userName = "在Entity Framework中实现指定字段更新11", a="aaaaa" };
// System.Reflection.PropertyInfo[] propertyInfos= tbTemp.GetType().GetProperties();
// db.tb1.Attach(tbTemp);
// var stateEntry= db.ObjectStateManager.GetObjectStateEntry(tbTemp);
// for (int i = 1; i < propertyInfos.Length - 1; i++)
// {
// Response.Write(propertyInfos[i].Name);
// //tateEntry.SetModifiedProperty(propertyInfos[i]);
// }

//// stateEntry.SetModifiedProperty("a");
// // db.SaveChanges();

//}
tb1 tbTemp1 = new tb1 { id = 45, userName = "在Entity Framework中实现指定字段更新1122", a = "aaaaa" };
ModifyFild<tb1>(tbTemp1, "userName", "a");
/*
* 生成的SQL语句
exec sp_executesql N'update [dbo].[tb1]
set [userName] = @0
where ([id] = @1)
',N'@0 varchar(50),@1 int',@0='在Entity Framework中实现指定字段更新1122',@1=45
*/

}
/// <summary>
/// 利用泛型修改指定字段,不需要先查询后修改,减少数据库往返,提高系统性能
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="fileds"></param>
private void ModifyFild<T>(T model, params string[] fileds)
{
using (testdbEntities db = new testdbEntities())
{
//var tbTemp = new tb1 { id = 45, userName = "在Entity Framework中实现指定字段更新11", a = "aaaaa" };
// System.Reflection.PropertyInfo[] propertyInfos = tbTemp.GetType().GetProperties();
Type Ttype = typeof(T);
// Response.Write(Ttype.Name);
db.AttachTo(Ttype.Name, model);
//db.tb1.Attach(tbTemp);
var stateEntry = db.ObjectStateManager.GetObjectStateEntry(model);
for (int i = 0; i < fileds.Length - 1; i++)
{
//Response.Write(fileds[i]);
stateEntry.SetModifiedProperty(fileds[i]);
}
db.SaveChanges();
}

}

protected void Button5_Click(object sender, EventArgs e)
{
/*
using (testdbEntities db = new testdbEntities())
{
tb1 tempModel = new tb1 { id=45 };
db.AttachTo("tb1",tempModel);
db.ObjectStateManager.ChangeObjectState(tempModel, EntityState.Deleted);
db.SaveChanges();
}

*exec sp_executesql N'delete [dbo].[tb1]
where ([id] = @0)',N'@0 int',@0=45
*/
//myContext context = new myContext();

//myTab r = context.myTab.First(p => p.ID == 1);

//Console.WriteLine(r.EntityState); //print:Unchanged

//context.DeleteObject(r);

//Console.WriteLine(r.EntityState); //print:Deleted

//context.SaveChanges();




using (testdbEntities db = new testdbEntities())
{
tb1 tempModel = new tb1 { id = 2 };
db.AttachTo("tb1", tempModel);
db.DeleteObject(tempModel);
db.SaveChanges();
}
}
}