2

我在我的 SharePoint 2010 解决方案中使用 xml 代码创建列表定义和列表实例。现在,每次我部署我的解决方案时,它都会删除列表并创建一个新列表。如果列表不存在,我只想创建它。

如何检查列表是否已存在以及将代码放在哪里?

我的列表定义和列表实例出现在我的一项功能的“功能中的项目”中。

4

4 回答 4

7

谢谢您的回答。我在位于列表实例文件夹中的 SharePointProjectItem.spdata 文件中找到了解决方案。将“DeploymentConflictResolutionBehavior”设置为“无”会阻止 Visual Studio 在每次部署时删除我的列表。

我的 SharePointProjectItem.spdata 文件现在如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ProjectItem Type="Microsoft.VisualStudio.SharePoint.ListInstance" DefaultFile="Elements.xml" SupportedTrustLevels="All" SupportedDeploymentScopes="Web, Site" xmlns="http://schemas.microsoft.com/VisualStudio/2010/SharePointTools/SharePointProjectItemModel">
  <Files>
    <ProjectItemFile Source="Elements.xml" Target="MyListInstance\" Type="ElementManifest" />
  </Files>
  <ExtensionData>
    <ExtensionDataItem Key="DeploymentConflictResolutionBehavior" Value="None" />
  </ExtensionData>
</ProjectItem>
于 2011-09-21T07:46:42.073 回答
1

There is no method currently included in SP object model to determine this. As Beytan mentioned, an extension method can help solve this issue. I think the example in this link is a better way to implement this type of extension method. It iterates through the entire collection of lists, returning true if it finds a match and false if it does not. The following is the code from the post.

public static class SPWebExtensions
{
    public static bool ListExists(this SPWeb web, string listName)
   {
          var lists = web.Lists;
          foreach (SPList list in lists)
          {
              if(list.Title.Equals(listName))
                  return true;
          }
          return false;
      }
  }

Since your list definitions and instances are already in a feature, you can call the extension method from the FeatureActivated method of the event receiver for your feature.

using(SPWeb web = (SPWeb)properties.Feature.Parent)
{
   if(!web.ListExists(listTitle))
   {
      //create the list.
   }
}
于 2011-09-21T01:07:08.273 回答
1

如何通过服务器端对象模型检查 SPList 是否存在:

//Verify if list exist by its Url 
public static bool ListExists(SPWeb web, string listUrl)
{
   return web.Lists.Cast<SPList>().Any(list =>  string.Equals(list.RootFolder.ServerRelativeUrl, listUrl));
}
于 2014-02-06T00:04:16.337 回答
1

从代码(web.Lists.Add)创建实例,并使用它来检查是否已经存在:web.Lists.TryGetList("listTitle")

于 2014-01-07T18:08:45.440 回答