views:

208

answers:

1

I have a question that I'm struggling with in ADO.NET Data Services:

When assembling an Entity for storage I need to get a related value from a lookup file. For example a person has a status code assigned of 'Pending' which is in a table called StatusCodes.

In Entity Framework, I'd need to set the value of person.StatusCode equal to an instance of the StatusCode. In the Entity Framework or in LINQ2Sql I'd so something like this:

      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);

The query for the statCode won't work in ADO.NET Data Services and I get a runtime error saying the function is not supported. I assume it's because the statCode lookup is not an Async call.

However,

      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);

doesn't work either due to the Async nature of the query, the result won't be back before the person save happens.

Am I approaching this correctly?

Thanks

A: 

After sleeping on this I came up with the following:

  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);

I can create a local copy of the status code and link it into the context. It's important to new up the appStatPending rather than doing a StatusCode.CreateStatusCode() since doing that will add a new StatusCode to the database when the person graph persisted. For the same reason it's important to do the AttachTo("StatusCodeSet", appStatPending) since doing myContext.AddToStatusCodeSet() will also add a new entry to the StatusCodes table in the database.