2017-04-13 45 views
0

我正在使用通用Repository和UnitOfWork模式來處理數據庫。設置Generic Repository中的列的值

現在我有如下的插入方法:

public virtual void Insert(TEntity entity) 
{ 
    //How to set up like this 
    entity.UpdatedDate = DateTime.Now.AddMonth(-1); 

    entity.ObjectState = ObjectState.Added; 
    _dbSet.Attach(entity); 
    _context.SyncObjectState(entity); 
} 

的實體是代表了一個表類,像這樣:

public partial class AM_User 
    { 
     public int UserID { get; set; } 
     public string UserName { get; set; } 
     public Nullable<System.DateTime> CreatedDate { get; set; } 
     public Nullable<System.DateTime> UpdatedDate { get; set; } 
    } 

實體有一個名爲CreatedDate列。我只想要一個地方輸入CreatedDate的值?我怎麼能使用反射器來設置它的價值?

回答

2

您可以通過反射回復:

typeof(TEntity).GetProperty("UpdatedDate").SetValue(entity, DateTime.Now.AddMonth(-1)); 
+0

這部分代碼真的很有幫助。 – gdmanandamohon

1

最安全的方法是確保所有的實體類實現相同的接口,例如:

public interface IEntity 
{ 
    DateTime CreatedDate { get; set; } 
} 

public class MyEntity : IEntity 
{ 
    public string Name { get; set; } 
    public DateTime CreatedDate { get; set; } 
} 

,改變你的資料庫,以對泛型類型的約束:

public class Repository<TEntity> where T : IEntity 
{ 
    //etc... 
} 

現在您的插入功能可以更改爲:

public virtual void Insert(TEntity entity) 
{ 
    entity.CreatedDate = DateTime.Now; 
    //etc... 
} 
+0

嗨DavidG,感謝您的幫助。但是我的實體是一個代表表格並由PowerTool生成的類,我不能根據你的建議創建一個實體。我更清楚地更新了問題。 請指教。 –

+0

實際上,因爲生成的類是部分的,您可以添加自己的文件來擴展該類並將接口添加到它。 – DavidG