LINQ :: 使用静态DataContext来防止并发问题
我在我的项目中面临一些问题。 当我尝试更新实体时,它给了我不同类型的错误。
我从网上读到的。 这些错误是因为
1 - 我从本地创建 DataContext 的方法获取实体类的对象
,并且在更新方法中 id 不会更新,因为这里在本地创建了另一个 DataContext。 (即使它不会抛出任何异常)
我发现很多与此问题相关的文章
1 - 在表中添加时间戳列(在我的项目中不起作用。我尝试过这个)
一个人说每个人都使用单个DataContext。
我通过创建以下课程来做到这一点,
public class Factory
{
private static LinqDemoDbDataContext db = null;
public static LinqDemoDbDataContext DB
{
get
{
if (db == null)
db = new LinqDemoDbDataContext();
return db;
}
}
}
public static Student GetStudent(long id)
{
LinqDemoDbDataContext db = Factory.DB;
//LinqDemoDbDataContext db = new LinqDemoDbDataContext();
Student std = (from s in db.Students
where s.ID == id
select s).Single();
return std;
}
public static void UpdateStudent(long studentId, string name, string address)
{
Student std = GetStudent(studentId);
LinqDemoDbDataContext db = Factory.DB;
std.Name = name;
std.Address = address;
db.SubmitChanges();
}
在本例中我想更新学生详细信息。
它解决了我的问题。 但现在的问题是。
在基于 Web 的应用程序中使用上述技术是个好方法吗???
i am facing some problems in my project. when i try to update entity it gives me different type of errors.
i read from net. these errors are because
1 - I am getting Object of entity class from method which creates DataContext locally
and in update method id does not update because here another DataContext is created locally.
(even it does not throw any exception)
i found many articles related to this problem
1 - Adding timestamp column in table (does not effect in my project. i tried this)
one guy said that use SINGLE DataContext for everyone.
i did this by creating the following class
public class Factory
{
private static LinqDemoDbDataContext db = null;
public static LinqDemoDbDataContext DB
{
get
{
if (db == null)
db = new LinqDemoDbDataContext();
return db;
}
}
}
public static Student GetStudent(long id)
{
LinqDemoDbDataContext db = Factory.DB;
//LinqDemoDbDataContext db = new LinqDemoDbDataContext();
Student std = (from s in db.Students
where s.ID == id
select s).Single();
return std;
}
public static void UpdateStudent(long studentId, string name, string address)
{
Student std = GetStudent(studentId);
LinqDemoDbDataContext db = Factory.DB;
std.Name = name;
std.Address = address;
db.SubmitChanges();
}
in this case i want to update student details.
it solved my problem. but now the question is.
Is it good approach to use above technique in Web Based application???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不。DataContext 不是线程安全的。 您无法在处理不同请求的不同线程之间安全地共享 1 个 DataContext。
另外 - 这种模式称为 Singleton,而不是 Factory
No. DataContext is not thread safe. You cannot share 1 DataContext among the different threads handling different requests safely.
Also - this pattern is called Singleton, not Factory