我已经看到了一个使用entiyt框架的示例,它起诉ApplyPropertyChanges方法来更新实体。在普通的旧Linq-To-SQL中是否存在等效方法?
我的应用程序是一个asp.net MVC应用程序,当我运行我的编辑操作时,我想只是调用sometihng:
originalObject = GetObject(id);
DataContext.ApplyPropertyChanges(originalObject, updatedObject);
DataContext.SubmitChanges();
答案 0 :(得分: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;
}
答案 1 :(得分:1)
var theObject = (from table in dataContext.TheTable
where table.Id == theId
select table).Single();
theObject.Property = "New Value";
dataContext.SubmitChanges();
您可以尝试使用Attach方法,但它有问题。请参阅此链接作为参考:LINQ to SQL Update