2011-04-04 93 views
1

我發現,這是從一個DataContext這是否是從DataContext更新實體的最佳方式?

public bool UpdateLead(Lead lead) 
    { 

     OrganizationServiceContext context = GetOrgContext(); 
     Lead leadToTrack = getLead(lead.Id, context); 
     leadToTrack.AccountId.Id = lead.AccountId.Id; 
     //... 
     context.UpdateObject(leadToTrack); 

     context.SaveChanges(); 

     return true; 
    } 

更新實體的方式,但我必須在實體約200場(感謝到Microsoft Dynamics CRM)。我是否必須寫出200行,如leadToTrack.Field1 = lead.Field1,還是有更簡潔的方法?

謝謝

回答

4

你可以使用AutoMapper這個 - 如果你有那麼多的屬性,基本上在兩邊都有相同的名字,這應該適合你。

+1

+1這是測繪工作,@Mathieu也看看ValueInjecter它可能使事情變得比AutoMapper您更輕鬆。 – 2011-04-04 18:53:38

1

你可以用反射做到這一點。這裏有一個類似的方法,我寫了這個目的:

public static FMVHistory CloneFMV(FMVHistory F) { 
     FMVHistory F_Clone = new FMVHistory(); 

     Type typeToClone = F.GetType(); 
     Type[] BadGenericTypes = new Type[] { typeof(EntityCollection<>), typeof(EntityReference<>) }; 
     Type[] BadTypes = new Type[] { typeof(System.Data.EntityKey) }; 

     foreach (PropertyInfo pi in typeToClone.GetProperties().Where(p => p.CanWrite)) { 
      if (pi.PropertyType.IsGenericType && BadGenericTypes.Contains(pi.PropertyType.GetGenericTypeDefinition()) 
       || (BadTypes.Contains(pi.PropertyType)) 
       || (pi.Name.Equals("nameOfYourPrimaryKeyWhichYouDontWantCloned"), StringComparison.CurrentCultureIgnoreCase))) 
       continue; 

      pi.SetValue(F_Clone, pi.GetValue(F, null), null); 
     } 
     return F_Clone; 
    } 

除,而不是在一個對象傳遞給被克隆,你會通過在源對象和目標對象,並從一個以上的值複製到另一個。

2

您可以將實體,並改變它的對象狀態的進入......

context.Leads.Attach(lead); 

ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(lead); 
entry.ChangeState(EntityState.Modified); 
context.SaveChanges(); 
相關問題