【问题标题】:LINQ to SQL, DataContext issueLINQ to SQL,DataContext 问题
【发布时间】:2011-01-23 14:42:12
【问题描述】:

在使用 LINQ to SQL 时,我在自定义类中创建了一个静态 DataContext,即

public class OPIS
 {
 public static DataContext DataContext = new DataContext();
 ....
}

现在每当我需要通过 LINQ 查询(包括插入和删除)结果时,我都会使用这个静态 DataContext 对象。直到我无法在其中一个 EntitySet 中获取最近插入的对象,我才发现问题,例如

我有一个Profile 和一个BasicInfo EntityType,它们之间是一对一的关系。

//Inserting a new BasicInfo Object, have created association with Profile object before
OPIS.DataContext.BasicInfos.InsertOnSubmit(basicInfoObject);

现在在另一个页面上

Profile profile = //get new profile from linq, comming fine

BasicInfo bi = profile.BasicInfo //returning null, it shouldn't

bi 应该返回一个与配置文件关联的 BasicInfo 对象,但事实并非如此。为什么?

【问题讨论】:

    标签: c# asp.net linq-to-sql


    【解决方案1】:

    您是否曾经在您的DataContext 上致电SubmitChanges()?如果没有,那么您所做的就是注册 BasicInfo 以进行插入,但永远不要插入它。

    OPIS.DataContext.BasicInfos.InsertOnSubmit(basicInfoObject); //registers object for insertion
    OPIS.DataContext.SubmitChanges(); // performs insert
    

    【讨论】:

    • @Sadi - 你有没有运气确定是什么导致了你的问题?
    猜你喜欢
    • 2011-01-13
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多