开发者

Is this de best way to update an entity from DataContext?

I've found that this is the way to update an entity from a DataContext

    public bool UpdateLead(Lead lead)
    {

        OrganizationServiceContext context = GetOrgContext();
        Lead leadToTrack = getLead(lead.Id, context);
        leadToTrack.AccountId.Id = lead.AccountI开发者_如何转开发d.Id;
        //...
        context.UpdateObject(leadToTrack);

        context.SaveChanges();

        return true;
    }

But I have about 200 fields in that entity (thanks to Microsoft Dynamics CRM). Do I have to write 200 lines like leadToTrack.Field1 = lead.Field1 or is there a more concise way?

Thanks


You could use AutoMapper for this - if you have that many properties that all basically have the same name on both sides this should work well for you.


You can attach the entity and change it's object state entry...

context.Leads.Attach(lead);

ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(lead);
entry.ChangeState(EntityState.Modified);
context.SaveChanges();


You can do that with reflection. Here's a similar method I wrote for that purpose:

    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;
    }

Except instead of passing in one object to be cloned, you'd pass in a source object, and a destination object, and copy the values over from one to the other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜