你可以這樣做。首先創建一些接口:
public interface IHasDatabaseName {
string Database { set; }
}
併爲有問題的實體執行。然後在構造函數中您DbContext
(或在任何地方,你建立你的DbContext
,如果使用例如DI容器),訂閱ObjectMaterialized
事件:
// this is DbContext here
((IObjectContextAdapter) this).ObjectContext.ObjectMaterialized += ObjectContextOnObjectMaterialized;
然後:
// this is DbContext here
private void ObjectContextOnObjectMaterialized(object sender, ObjectMaterializedEventArgs objectMaterializedEventArgs) {
var dbName = objectMaterializedEventArgs.Entity as IHasDatabaseName;
if (dbName != null) {
dbName.Database = this.Database.Connection.Database;
}
}
來源
2016-11-08 20:32:31
Evk
我可以」不要修改存儲層,因爲我希望每個類都有這個值,這將是一個太大的承諾。 – Keith