0

我在 ADO.NET 数据服务中遇到了一个问题:

在组装实体进行存储时,我需要从查找文件中获取相关值。例如,一个人的状态代码分配为“待定”,该状态代码位于名为 StatusCodes 的表中。

在 Entity Framework 中,我需要将 person.StatusCode 的值设置为 StatusCode 的一个实例。在实体框架或 LINQ2Sql 中,我会这样:

      var person = Person.CreatePerson(stuff);

  var statCode = myContext.StatusCodeSet.Where(sc => sc.Description == "Pending").FirstOrDefault();

  person.StatusCode = statCode;

  // ...more code here...

  myContext.BeginSaveChanges(SaveChangesOptions.Batch,

                                new AsyncCallback(OnSaveAllComplete),

                                null);

statCode 查询在 ADO.NET 数据服务中不起作用,并且我收到运行时错误,指出该函数不受支持。我认为这是因为 statCode 查找不是异步调用。

然而,

      var person = Person.CreatePerson(stuff);
  var query = from stat in myContext.StatusCodeSet
              where stat.Description == "Pending"
              select stat;
  var dsQuery = (DataServiceQuery<StatusCode>)query;
  dsQuery.BeginExecute(
      result => tutorApplication.StatusCode = dsQuery.EndExecute(result).FirstOrDefault(), null);
  // ...more code here...
  myContext.BeginSaveChanges(SaveChangesOptions.Batch,
                            new AsyncCallback(OnSaveAllComplete),
                            null);

由于查询的异步性质,也不起作用,在人员保存发生之前结果不会返回。

我正确地接近这个吗?

谢谢

4

1 回答 1

0

在睡了这个之后,我想出了以下几点:

  var person = Person.CreatePerson(stuff);
  var appStatPending = new StatusCode()
  {
    StatusCodeId = (int)StatusCodes.Pending,
    Code = "Pending",
    Description = "Pending",
    EffectiveDate = DateTime.Now,
    EnteredBy = "",
    EnteredDate = DateTime.Now
  };

  myContext.AttachTo("StatusCodeSet", appStatPending);
  person.StatusCode = appStatPending;
  myContext.SetLink(tutorApplication, "StatusCode", appStatPending);


  // ...more code here...  
  myContext.BeginSaveChanges(SaveChangesOptions.Batch,
    new AsyncCallback(OnSaveAllComplete),
    null);

我可以创建状态代码的本地副本并将其链接到上下文中。重要的是更新 appStatPending 而不是执行 StatusCode.CreateStatusCode() ,因为这样做会在人员图持续存在时将新的 StatusCode 添加到数据库中。出于同样的原因,执行 AttachTo("StatusCodeSet", appStatPending) 很重要,因为执行 myContext.AddToStatusCodeSet() 还将向数据库中的 StatusCodes 表添加一个新条目。

于 2009-03-18T09:52:26.553 回答