2010-06-18 99 views
2

我对.NET 3.5 Web应用程序上的某些管理页面使用动态数据和LINQ to SQL。我所有的管理表都有一个CreatedBy,CreatedDate,UpdatedBy和UpdatedDate。LINQ to sql动态数据在插入和更新之前修改对象

我正在寻找一种方法来在插入和更新对象之前注入这些属性的设置。

我见过一个object_inserting钩子,如果你有一个LINQ到Web表单中的SQL数据源,但我使用动态数据...有没有一种简单的方法来一般地设置?我还研究过修改每个管理对象的部分类,但是我看到的最接近的钩子是使用Insert操作实现OnValidate方法。有什么建议么? TIA。

回答

2

大卫·特维已发表在你的实体的OnSaving和OnSaved方法添加的一个很好的例子,点击这里:Adding OnSaving an OnSaved Events to LINQ to SQL Entities

通过实现你的实体上面,你可以用一个部分类,例如扩展它们

partial class MyAdminEntity : EntityBase 
{ 
    internal override OnSaving(ChangeAction changeAction) 
    { 
    if (changeAction == ChangeAction.Insert) 
    { 
     CreatedBy = "<username>"; 
     CreatedDate = DateTime.Now; 
    } 
    else if (changeAction == ChangeAction.Update) 
    { 
     CreatedBy = "<username>"; 
     CreatedDate = DateTime.Now; 
    } 
    } 
} 
1

我知道这是一个旧帖子,但这可以帮助他人解决他们的问题。

还有其他一些方法可以做到这一点。 您可以使用此:

public partial class BasicModelDataContext : DataContext 
{ 
     partial void InsertEmployee(Employee instance) 
     { 
      instance.MyValue = "NEW VALUE"; 
      Employee.Insert(instance); 
     } 

     partial void UpdateEmployee(Employee instance) 
     { 
      instance.MyValue = "NEW Update VALUE"; 
      Employee.Update(instance); 
     } 
} 
2

我得到了尝试,加入你的实体类的app_code,类更改为部分类,它为我的作品!希望这个帮助! Reference here

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Data; 
using System.Data.Objects; 
using System.Data.Linq; 
using System.ComponentModel; 
using System.ComponentModel.DataAnnotations; 

namespace NorthwindModel 
{ 

    public partial class NorthwindEntities 
    { 
     partial void OnContextCreated() 
     { 
      // Register the handler for the SavingChanges event. 
      this.SavingChanges += new EventHandler(context_SavingChanges); 
     } 

     // SavingChanges event handler. 
     private static void context_SavingChanges(object sender, EventArgs e) 
     { 
      var objects = ((ObjectContext)sender).ObjectStateManager; 

      // Get new objects 
      foreach (ObjectStateEntry entry in objects.GetObjectStateEntries(EntityState.Added)) 
      { 
       // Find an object state entry for a SalesOrderHeader object. 
       if (entry.Entity.GetType() == typeof(Employee)) 
       { 
        var usr = entry.Entity as Employee; 

        // Do your Business Logic here. 
       } 
      } 
     } 
    } 
}