LINQ to SQL缓存问题

时间:2010-09-03 04:53:41

标签: linq caching

这应该很简单。

我让LINQ to SQL(C#3.5 / SQL Server)运行良好,在两个表会议 ConferenceAttendees 之间建立了简单的关系。

我已经创建并提交了会议,然后使用以下代码添加3 ConferenceAttendees (重复3次):

ConferenceAttendee NewAttendee = new ConferenceAttendee();
NewAttendee.ConferenceId = ConferenceID;
NewAttendee.Name = ContactName;
NewAttendee.Email = ContactEmail;
db.ConferenceAttendees.InsertOnSubmit(NewAttendee);
db.SubmitChanges();

效果很好,我看到3位新与会者出现在数据库中。

更新: 然后,使用全新的datacontext,我尝试以下方法:

string Names = String.Empty;
Conference RequestedConference = db.Conferences.FirstOrDefault(x => x.ConferenceId == ConferenceID);
   foreach (ConferenceAttendee Attendee in RequestedConference.ConferenceAttendees)
      Names += Attendee.Name + ", ";

但它没有附加任何相关的参加者! (它们肯定存在于数据库中并且已经提交)。但RequestedConference.ConferenceAttendees的计数总是为0,因此永远不会输入循环。

foreach (ConferenceAttendee Attendee in this.ConferenceAttendees)
{ Names += Attendee.Name; }

我在Partial Class Conference中这样做,我使用了一个名为PrintAllAttendeeNames()的方法。

我做错了什么,为什么这个新的datacontext在数据库提交时已经通过LINQ很容易看到这些相关对象?

(注意:我已经尝试过调用

db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues);

无济于事..)

非常感谢

CONFESSION 更新

我是一个绝对的白痴。我将dataContext设置为静态。我通常从不这样做,这就是为什么我通常不会遇到延迟加载的问题。

我有这个:

public static MyDataContext db = new MyDataContext(ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString);

当然,改成它可以解决问题!!!

public MyDataContext db = new MyDataContext(ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString);

1 个答案:

答案 0 :(得分:1)

一些事情。首先,您只应在完成所有更改后提交更改。每次创建新与会者时都不需要致电SubmitChanges。首先创建所有三个,InsertOnSubmit每个,然后只调用SubmitChanges。 LINQ to SQL将以这种方式生成更高效,更笨重的调用。

其次,我对与会者加载问题有点困惑。他们应该在Attendee属性的第一次访问时延迟加载。每个会议在首次访问其属性时都会产生单独的查询,因此这不是处理它的最有效方法。您可以告诉L2S为您加载的每个会议对象预加载所有与会者。您可以使用DataLoadOptions类执行此操作:

using (var context = new SomeContext(...))
{
    var options = new DataLoadOptions();
    options.LoadWith<Conference>(c => c.ConferenceAttendees);

    context.LoadOptions = options;

    var conferencesWithAttendees = from c in context.Conferences
                                   where c.Year = DateTime.Now.Year
                                   select c;

    foreach (var conferenceWithAttendee in conferencesWithAttendees)
    {
        conferenceWithAttendee.PrintAllAttendeeNames();
    }
}