2010-06-18 64 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. 
       } 
      } 
     } 
    } 
}