C#在上下文之外保存实体对象
我有一个来自以下linq查询的记录:C#在上下文之外保存实体对象,c#,linq,entity-framework,C#,Linq,Entity Framework,我有一个来自以下linq查询的记录: using (var context = new myEntities()) { var record = (from d in context.Student select d).SingleOrDefault(); } 我通常为记录分配一个新值,如下所示: record.Value = SomeNewValue; context.SaveChanges(record); static class Utilities { publi
using (var context = new myEntities())
{
var record = (from d in context.Student select d).SingleOrDefault();
}
我通常为记录分配一个新值,如下所示:
record.Value = SomeNewValue;
context.SaveChanges(record);
static class Utilities
{
public static void SaveChanges( this MyEntity entity, Student record, Student SomeNewValue )
{
record.Value = SomeNewValue;
entity.SaveChanges;
}
}
然后我会做一个
context.SaveChanges;
这一切都很好。我的问题是:如果我将同一条记录传递给另一个函数,或者如果该记录是从一个函数返回的,如何保存该记录?我在找这样的东西:
record.Value = SomeNewValue;
context.SaveChanges(record);
static class Utilities
{
public static void SaveChanges( this MyEntity entity, Student record, Student SomeNewValue )
{
record.Value = SomeNewValue;
entity.SaveChanges;
}
}
触发相关函数的操作应创建并管理
上下文
。如果是ASP.NET MVC应用程序,我建议您在请求开始时设置上下文,并在请求完成时调用context.SaveChanges
。在winforms/WPF应用程序中,您可能希望在应用程序的整个生命周期中保留上下文
,并在任何可能更改数据的操作(如按下按钮)后调用context.SaveChanges()
触发相关函数的操作应创建和管理上下文。如果是ASP.NET MVC应用程序,我建议您在请求开始时设置上下文,并在请求完成时调用context.SaveChanges
。在winforms/WPF应用程序中,您可能希望在应用程序的整个生命周期中保留上下文
,并在任何可能更改数据的操作(如按下按钮)后调用context.SaveChanges()
你是说你有一个类对象要处理吗?如果是:
myEntities.Student.AddObject(student); //Where student is of type Student
或者,如果您还没有,请动态创建一个:
myEntities.Student.AddObject(new Student()
{
Name = formData[Name],
GPA = GetGPA(),
Major = Convert.ToString(Major)
});
但在此之后,您仍然必须调用SaveChanges
或者…
如果跟踪对象并在上述上下文之外使用它们,则可以修改属性的访问器,以便在修改对象的属性时调用SaveChanges()
方法并提交更改。只是想一想
进一步阅读材料:
你的意思是你有一个类对象要处理吗?如果是:
myEntities.Student.AddObject(student); //Where student is of type Student
或者,如果您还没有,请动态创建一个:
myEntities.Student.AddObject(new Student()
{
Name = formData[Name],
GPA = GetGPA(),
Major = Convert.ToString(Major)
});
但在此之后,您仍然必须调用SaveChanges
或者…
如果跟踪对象并在上述上下文之外使用它们,则可以修改属性的访问器,以便在修改对象的属性时调用SaveChanges()
方法并提交更改。只是想一想
进一步阅读材料:
也许你喜欢这样的东西:
record.Value = SomeNewValue;
context.SaveChanges(record);
static class Utilities
{
public static void SaveChanges( this MyEntity entity, Student record, Student SomeNewValue )
{
record.Value = SomeNewValue;
entity.SaveChanges;
}
}
因此,您可以调用如下函数:
context.SaveChanges(record, SomeNewValue);
也许你会喜欢这样的东西:
record.Value = SomeNewValue;
context.SaveChanges(record);
static class Utilities
{
public static void SaveChanges( this MyEntity entity, Student record, Student SomeNewValue )
{
record.Value = SomeNewValue;
entity.SaveChanges;
}
}
因此,您可以调用如下函数:
context.SaveChanges(record, SomeNewValue);
将记录添加到上下文,但不添加到database@Boomer哈-你和我的想法一样。刚刚添加了最后一条评论。=)将记录添加到上下文,但不添加到database@Boomer哈-你和我的想法一样。刚刚添加了最后一条评论。=)你是说你对那条记录做了另一次修改吗?你是说你对那条记录做了另一次修改吗?我把上下文作为类的模块级变量。这会奏效的。这使上下文成为类的模块级变量。这会奏效的。Th