这篇文章主要为大家详细介绍了ADO.NET EF中的实体修改方法,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随四海网的小编两巴掌来看看吧!
1.传统修改模式,看下列代码代码如下:
using (NorthwindEntities context = new NorthwindEntities())
{
Region region = context.Region.FirstOrDefault(v => v.RegionID == 4);
region.RegionDescription = "Test";
context.SaveChanges();
}
代码如下:
SQL1:SELECT TOP 1 [Extent1].[RegionID] AS [RegionID], [Extent1].[RegionDescription] AS [RegionDescription]FROM [dbo].[Region] AS [Extent1]WHERE 4 = [Extent1].[RegionID]
SQL2:exec sp_executesql N'update [dbo].[Region]set [RegionDescription] = @0where ([RegionID] = @1)', N'@0 nchar(4),@1 int', @0 = N'Test', @1 = 4
代码如下:
Region region;
using (NorthwindEntities context = new NorthwindEntities())
{
region = context.Region.FirstOrDefault(v => v.RegionID == 4);
}
using (NorthwindEntities context = new NorthwindEntities())
{
region.RegionDescription = "Test";
context.SaveChanges();
}
代码如下:
Region region;
using (NorthwindEntities context = new NorthwindEntities())
{
region = context.Region.FirstOrDefault(v => v.RegionID == 4);
}
using (NorthwindEntities context = new NorthwindEntities())
{
Region newRegion = context.Region.FirstOrDefault(v => v.RegionID == region.RegionID);
region.RegionDescription = "Test";
context.SaveChanges();
}
代码如下:
Region region;
using (NorthwindEntities ne = new NorthwindEntities())
{
//利用EntityObject.Execute(MergeOption.NoTracking),等效于使用ObjectContext.Dettach(EntityObject)
//查询并分离对象
region = ne.Region.Execute(MergeOption.NoTracking).Where(v => v.RegionID == 1).FirstOrDefault();
}
//修改分离的值
region.RegionDescription = "TestTest1";
//使用分离的对象 order 更新
using (NorthwindEntities context = new NorthwindEntities())
{
//将数据载入到context中以便更新
context.GetObjectByKey(region.EntityKey);
//使用order 更新 context中的对应对象
context.ApplyPropertyChanges(region.EntityKey.EntitySetName, region);
context.SaveChanges();
}
代码如下:
SQL1:exec sp_executesql N'SELECT [Extent1].[RegionID] AS [RegionID], [Extent1].[RegionDescription] AS [RegionDescription] FROM [dbo].[Region] AS [Extent1] WHERE [Extent1].[RegionID] = @p0', N'@p0 int', @p0 = 1
SQL2:exec sp_executesql N'update [dbo].[Region] set [RegionDescription] = @0where ([RegionID] = @1) ', N'@0 nchar(9),@1 int', @0 = N'TestTest1', @1 = 1
代码如下:
using (NorthwindEntities context = new NorthwindEntities())
{
Region region = context.Region.FirstOrDefault(v => v.RegionID == 4);
context.Detach(region);
region.RegionDescription = "因为测试";
context.Attach(region);
var newRegion = context.ObjectStateManager.GetObjectStateEntry(region);
newRegion.SetModified();
newRegion.SetModifiedProperty("RegionDescription");
context.SaveChanges();
}
代码如下:
exec sp_executesql N'update [dbo].[Region]set [RegionDescription] = @0where ([RegionID] = @1)', N'@0 nchar(4),@1 int', @0 = N'因为测试', @1 = 4
本文来自:http://www.q1010.com/179/7373-0.html
注:关于ADO.NET EF中的实体修改方法的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:SQL SERVER
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。