基於@ sky-dev實現創建基類。所以這可以很容易地應用於多個上下文和實體。
public abstract class BaseDbContext<TEntity> : DbContext where TEntity : class
{
public BaseDbContext(string connectionString)
: base(connectionString)
{
}
public override int SaveChanges()
{
UpdateDates();
return base.SaveChanges();
}
private void UpdateDates()
{
foreach (var change in ChangeTracker.Entries<TEntity>())
{
var values = change.CurrentValues;
foreach (var name in values.PropertyNames)
{
var value = values[name];
if (value is DateTime)
{
var date = (DateTime)value;
if (date < SqlDateTime.MinValue.Value)
{
values[name] = SqlDateTime.MinValue.Value;
}
else if (date > SqlDateTime.MaxValue.Value)
{
values[name] = SqlDateTime.MaxValue.Value;
}
}
}
}
}
}
用法:
public class MyContext: BaseDbContext<MyEntities>
{
/// <summary>
/// Initializes a new instance of the <see cref="MyContext"/> class.
/// </summary>
public MyContext()
: base("name=MyConnectionString")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MyContext"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public MyContext(string connectionString)
: base(connectionString)
{
}
//DBcontext class body here (methods, overrides, etc.)
}
我改變了我的datacolumns和現在使用typeof ...進一步,我發現我的問題。有1個datarow包含錯誤的日期,從而觸發了錯誤 – Gerbrand 2009-08-26 05:46:33