在发布到文档库后获取项目的ID

本文关键字:获取 项目 ID 文档 | 更新日期: 2023-09-27 18:14:51

我目前正在使用c#中的WCF数据服务(一个asp.net mvc4应用程序)从Sharepoint 2010中获取信息。

对于常规的Sharepoint列表项,当将更改保存到上下文时,新项的id将自动填充到原始对象上。意义:

SomeContext context = /* creation of the context*/;
var someEntity = new SomeEntity {...};
context.AddToSomeEntityItems(someEntity);
context.SaveChanges();
var newId = someEntity.Id;      //this will have the new id

但是,如果您正在创建的是文档库的项,则id似乎不会在保存的实体上更新。例如:

SomeContext context = /* creation of the context*/;
var someOtherEntity = new SomeOtherEntity {...};
Stream data = /* some stream*/;
context.AddToSomeOtherEntityItems(someOtherEntity);
context.SetSaveStream(someOtherEntity, data, true, "SomeMIMEType", "SomeSlugPath");
context.SaveChanges();
var newId = someOtherEntity.Id;         //this will instead always have 0

我最初认为这是WCF数据服务的第一个版本中的错误,所以我更新到最新的5.4.0。但行为似乎是一样的。

我更愿意避免在负载过重时最终可能失败的奇怪查找,例如使用.OrderByDescending(x => x.Id).First()来获取最近创建的项。

当使用Fiddler查看实际的网络流量时,我可以看到二进制数据的初始上传实际上确实返回了项目的信息及其ID。如果我在保存更改之前使用SetLink配置该项目的其他关系,它们将被正确链接,因此上下文将相应地处理该值。

当项目用于文档库时,是否有任何方法可以让WCF数据服务更新实体上的ID ?

在发布到文档库后获取项目的ID

通常,我在插入之前手动设置Id

someOtherEntity.Id = Guid.NewGuid();

这样您也可以更容易地进行TDD。我认为最好是把责任留给你的代码,而不是依靠外部存储系统来告诉你Id是什么。

我正在做的是从响应头解析出id:

var responses = context.SaveChanges();
var created = responses.FirstOrDefault(r => r.StatusCode == (int)HttpStatusCode.Created);
if (response != null)
{
    var location = response.Headers.First(h => h.Key == "Location").Value;
    //location will be http://sharepoint.url/site/_vti_bin/ListData.svc/{listname}(id)
    //you can parse out the id from the end of that string
}