2012-05-23 77 views
1

我在寫一個簡單的應用程序,將實體導入CRM。 Durring此導入我需要將導入的實體(自定義實體)關聯到另一個(也是自定義)實體。Crm 2011 - 檢索關聯的[N:N]實體(C#)

新對象沒有問題,但是當我嘗試更新時,我需要刪除關於導入實體的所有關聯,並根據導入的數據重新創建它們。

我該怎麼做?

我正在考慮獲取所有關聯的實體,然後爲其中的每個實體調用disassociate,但是我試圖獲取這些關聯的實體。

我該如何解決這個問題?

+0

我想我已經找到了解決辦法: – user1412690

+0

http://mscrmkb.blogspot.com/2010/12/crm-2011-retrieve-related-entity-data.html – user1412690

回答

0

假設你有學生實體,要學生Cources複製到另一個自定義實體如你所說命名CStudent
您可以使用下面的代碼:

var scs = Context.new_Student_CourcesSet.Where(x => x.new_courceid == Cource.Id).ToList<new_Student_Cources>(); 

var removedsc = Context.new_new_CStudent_CourcesSet.Where(x => x.new_cstudentid == CStudent.Id).ToList<new_CStudent_Cources>(); 

EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); 
EntityReferenceCollection removedrelatedEntities = new EntityReferenceCollection(); 
Relationship relationship = new Relationship(new_CStudent_Cources.EntityLogicalName); 

if (removedsc != null) 
{ 
    foreach (new_CStudent_Cources c in removedsc) 
    { 
     RemovedrelatedEntities.Add(new EntityReference(new_Cources.EntityLogicalName, (Guid)ar.new_courcesid)); 
    } 

    Service.Disassociate(CStudent.LogicalName, CStudnetid, relationship, RemovedrelatedEntities); 
} 

foreach (new_Student_Cources d in scs) 
{ 
    relatedEntities.Add(new EntityReference(new_Cources.EntityLogicalName, (Guid)d.new_courceid)); 
} 

Service.Associate(CStudent.LogicalName, CStudentid, relationship, relatedEntities);