2009-09-17 5 views
3

J'ai vu un exemple utilisant l'infrastructure d'entiyt et il a poursuivi la méthode ApplyPropertyChanges pour mettre à jour une entité. Existe-t-il une méthode équivalente dans le vieux Linq-To-SQL?Existe-t-il un ApplyPropertyChanges avec un datacontext?

Mon applicaiton est une application asp.net MVC et quand je lance mon action Edit je veux simplement appeler sometihng comme:

originalObject = GetObject(id); 
DataContext.ApplyPropertyChanges(originalObject, updatedObject); 
DataContext.SubmitChanges(); 

Répondre

2

Cette méthode devrait faire ce que vous avez besoin:

public static void Apply<T>(T originalValuesObj, T newValuesObj, params string[] ignore) 
    where T : class 
{ 
    // check for null arguments 
    if (originalValuesObj == null || newValuesObj == null) 
    { 
     throw new ArgumentNullException(originalValuesObj == null ? "from" : "to"); 
    } 

    // working variable(s) 
    Type type = typeof(T); 
    List<string> ignoreList = new List<string>(ignore ?? new string[] { }); 

    // iterate through each of the properties on the object 
    foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) 
    { 
     // check whether we should be ignoring this property 
     if (ignoreList.Contains(pi.Name)) 
     { 
      continue; 
     } 

     // set the value in the original object 
     object toValue = type.GetProperty(pi.Name).GetValue(newValuesObj, null); 
     type.GetProperty(pi.Name).SetValue(originalValuesObj, toValue, null); 
    } 

    return; 
} 
+0

c'est sérieusement le moyen le plus facile de le faire? c'est littéralement une ligne dans EF. – dnord

1
var theObject = (from table in dataContext.TheTable 
       where table.Id == theId 
       select table).Single(); 

theObject.Property = "New Value"; 
dataContext.SubmitChanges(); 

Vous pouvez essayer d'utiliser la méthode attach mais il est bogué . S'il vous plaît voir ce lien comme référence: LINQ to SQL Update

+0

Je dois mettre à jour tous les biens individuellement? Existe-t-il une manière réutilisable de faire ceci pour n'importe quel objet yype? – littlechris

Questions connexes