2009-09-17 27 views
3

我看到一个使用entiyt框架的例子,它控制了ApplyPropertyChanges方法来更新一个实体。在普通的旧Linq-To-SQL中是否存在等价方法?是否有一个带有datacontext的ApplyPropertyChanges?

我的应用程序是有一个asp.net MVC应用程序,当我跑我的编辑操作我只想叫sometihng这样的:

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

回答

2

这个方法应该做你需要什么:

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

这是严肃的最平滑的方式吗?这实际上是EF中的一条线。 – dnord

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

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

你可以尝试使用连接方法,但它是越野车。请参阅此链接作为参考:LINQ to SQL Update

+0

所以,我必须单独更新每个属性?对于任何对象yype,是否有任何可重复使用的方法? – littlechris

相关问题