2012-08-08 143 views
0

我有兩個相同的SharePoint列表。我使用C#循環遍歷一個,並使用SP對象模型添加到另一個。C#檢查SharePoint列表項是否已經存在.. CAML?

問題是我不希望添加到其他的,如果已經有一個列表條目相匹配的從列表3個特定字段。

如何能做到這一點是在C#?使用CAML?

說我的表被並稱爲和字段名爲a,b和c。

在這裏,我不想一個條目添加到「到」,如果已經有在用A,B和C匹配我目前從條目的條目。

SPList fList = web.GetList("/sites/xxxx/Lists/from"); 
SPList tList = web.GetList("/sites/xxxx/Lab/Lists/to"); 

foreach (SPListItem fListItem in fList.Items)  
{ 
    // my caml code here i suspect? 
    //SPquery.query = "CAML"; 
    //SPList<yourlist>.GetItems(SPQuery object) 

    SPListItem tListItem = tList.Items.Add();  
    foreach (SPField field in fList.Fields)  
    {     
try 

回答

1

我開始使用SPMetal(如果可能,LINQ到SharePoint)。

MyContext context = new MyContext(SPContext.Current.Web.Url); 

var fItems = from f in context.FromList 
     select f; 

foreach(FItem fitem in fItems) 
{ 
    var toFoundItems = from t in context.ToList 
       where t.Field1 == fitem.Field1 && t.Field2 == fitem.Field2 && t.Field3 == fitem.Field3 
       select t; 

    if(t.Count > 0) 
     continue; 
    else 
     //Code to add items can use context to do this here also 
    } 

另一種方式是像你提到和使用SPQuery。

SPQuery query = new SPQuery(); 
query.Query = string.format(" 
<Where> 
    <AND> 

     <Eq> 
      <FieldRef Name='Field1' /> 
      <Value Type='Text'>{0}</Value> 
     </Eq> 
     <And> 
      <Eq> 
       <FieldRef Name='Field2' /> 
       <Value Type='Text'>{1}</Value> 
      </Eq> 
      <Eq> 
       <FieldRef Name='Field3' /> 
       <Value Type='Text'>{2}</Value> 
      </Eq> 
     </And> 
    </And> 
</Where>"); 

    SPListItemCollection items = tList.GetItems(query); 

if(items.Count > 0) 
    continue; 
else 
    //Code to add item 

我不是在我的正常PC,所以我無法測試這兩種代碼,但應該給你如何開始的想法,但不幸的是,的SharePoint不允許複合唯一鍵。

如果您想從不同的角度來處理問題,可以使用該列表上的事件接收器強制執行組合唯一鍵。

+0

謝謝。這意味着我們在SP2007上,所以我認爲沒有LINQ。 – o365spo 2012-08-08 15:00:58

+0

我已經問了一個相關的問題。可以從SPD生成的SPDatasource中獲得一個計數,並使用C#生成一個過濾器生成CAML?最簡單的方法是什麼?謝謝。 – o365spo 2012-08-08 18:23:52

+0

是否存在某種使用CAML內部單個qoutes的問題,如下所示..我在此查詢中返回每一行時,我應該只返回1行 o365spo 2012-08-09 21:16:37

相關問題