在ADO.NET数据服务中,我有一个正在努力解决的问题:
在组装要存储的实体时,我需要从查找文件中获取相关值。例如,一个人在一个名为StatusCodes的表中分配了一个状态代码'Pending‘。
在实体框架中,我需要将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);在ADO.NET数据服务中,对statCode的查询将不起作用,并且我得到一个运行时错误,指出该函数不受支持。我认为这是因为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);由于查询的异步性质,也不能工作,在保存person之前不会返回结果。
我的方法正确吗?
谢谢
发布于 2009-03-18 09:52:27
在睡了一觉之后,我想出了以下几点:
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(),因为这样做会在person图持久化时向数据库添加一个新的StatusCode。出于同样的原因,执行AttachTo("StatusCodeSet",appStatPending)也很重要,因为执行myContext.AddToStatusCodeSet()还会向数据库中的StatusCodes表添加一个新条目。
https://stackoverflow.com/questions/655531
复制相似问题