Asp.net linq将实体更新记录到数据库
这是我找到的更新代码:Asp.net linq将实体更新记录到数据库,asp.net,linq,entity-framework,linq-to-entities,Asp.net,Linq,Entity Framework,Linq To Entities,这是我找到的更新代码: using (TestDBEntities ctx = new TestDBEntities()) { //Get the specific employee from Database Emp e = (from e1 in ctx.Emp where e1.Name == "Test Employee" select e1).First(); //Change the Employee Name in m
using (TestDBEntities ctx = new TestDBEntities())
{
//Get the specific employee from Database
Emp e = (from e1 in ctx.Emp
where e1.Name == "Test Employee"
select e1).First();
//Change the Employee Name in memory
e.Name = "Changed Name";
//Save to database
ctx.SaveChanges();
}
我现在做的是这样的:
using(CRNNSTestEntities crnnsupContext = new CRNNSTestEntities())
{
CPersonalInfo t = ((IQueryable<CPersonalInfo>)Cache["personquery"]).First();
t.Tombstone.Address = Address1.Text;
System.Windows.Forms.MessageBox.Show(crnnsupContext.SaveChanges()+"");
};
使用(crnnstestanties crnnsupContext=new crnnstestanties())
{
CPersonalInfo t=((IQueryable)缓存[“personquery”]).First();
t、 墓碑。地址=地址1。文本;
System.Windows.Forms.MessageBox.Show(crnnsupContext.SaveChanges()+);
};
这不管用。所以我的问题是我是否必须写一些类似于cpersonalinfot=fromtin….
为什么我的方法不起作用
谢谢您需要从
crnnsupContext
中获取实体CPersonalInfo t
,而不是从缓存中获取该实体您还可以将对象附加到上下文
更多信息如何使用“附加”您可以更改此选项吗
使用(TestDBEntities ctx=newtestdbentities())
{
//从数据库中获取特定员工
Emp e=(从ctx.Emp中的e1开始)
其中e1.Name==“测试员工”
选择e1).First();
//更改内存中的员工姓名
e、 Name=“更改名称”;
//保存到数据库
ctx.SaveChanges();
}
这是否意味着每次我要更新记录时,都必须先运行搜索查询?@pita-是的,您需要从调用SaveChanges()的上下文中检索记录。在更新/删除对象之前,将对象附加到上下文是Julia Lerman和Rowan Miller描述的一种可能性(微软ADO.NET实体框架团队的程序经理)在第47页的“编程实体框架:DbContext”中-