我对 ObjectContext.SaveChanges 方法有疑问:
public void Save(Action<object, object> action)
{
EventAggregator.GetEvent<EntityServiceRequestingEvent>().Publish(true);
var bw = new BackgroundWorker();
var saved = false;
bw.DoWork += (o, ee) =>
{
ProgramStatusService.Status = Resources.DatabaseSavingMessage;
if (!CanSave())
{
throw new InvalidOperationException(
"You must not call Save when CanSave returns false.");
}
try
{
lock (Context)
{
Context.SaveChanges();
saved = true;
}
}
catch (ValidationException e)
{
MessageService.ShowError(null, string.Format(CultureInfo.CurrentCulture,
Resources.SaveErrorInvalidEntities,
e.Message));
}
catch (UpdateException e)
{
var innerException = e.InnerException as SqlException;
if (innerException != null && innerException.Number == 2601)
{
MessageService.ShowError(null, string.Format(CultureInfo.CurrentCulture,
Resources.DublicateKeyUpdateError,
e.InnerException.Message));
}
else
{
MessageService.ShowError(null, string.Format(CultureInfo.CurrentCulture,
Resources.SaveErrorInvalidFields,
e.InnerException.Message));
}
}
ee.Result = saved;
};
bw.RunWorkerCompleted += (o, e) =>
{
EventAggregator.GetEvent<EntityServiceRequestingEvent>().Publish(false);
ProgramStatusService.Status = Resources.ProgramReadyMessage;
if (e.Result != null) action.Invoke(this, e.Result);
};
bw.RunWorkerAsync();
}
保存时出现错误:调用线程无法访问此对象,因为不同的线程拥有它。在 Designer.cs 中:
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.DateTime> MDate
{
get
{
return _MDate;
}
set
{
OnMDateChanging(value);
ReportPropertyChanging("MDate");
_MDate = StructuralObject.SetValidValue(value);
ReportPropertyChanged("MDate");// **ERROR HERE**
OnMDateChanged();
}
}
如何正确使用 ObjectContext 和 BackgroundWorker?