如何在不使用ON DELETE CASCADE的情况下删除数据库中的所有记录?

时间:2016-09-28 00:25:14

标签: c# asp.net sql-server entity-framework foreign-keys

你能否帮我解决以下问题?

在我的项目中,应该允许网站的管理员用户通过单击按钮清空数据库。但是,这也不会假设修改架构。数据库包含一组彼此之间具有多个外键关系的表。我决定不选择级联删除以避免丢失必要的数据。

这是我的一段代码:

db.Posturi.RemoveRange(db.Posturi.ToList());
db.NumereRezervate.RemoveRange(db.NumereRezervate.ToList());
db.SaveChanges();

到目前为止,我因外键而出错:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
An error occurred while updating the entries. See the inner exception for details.
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at Users.stergere.SaveChanges(DbContext context) in D:\INTUIT\Daily Business\Users\Users\stergere.aspx.cs:line 135
   at Users.stergere.callPnl_Callback(Object sender, CallbackEventArgsBase e) in D:\INTUIT\Daily Business\Users\Users\stergere.aspx.cs:line 96
   at DevExpress.Web.ASPxCallbackPanel.OnCallback(CallbackEventArgsBase e)
   at DevExpress.Web.ASPxCallbackPanel.RaiseCallbackEvent(String eventArgument)
   at DevExpress.Web.ASPxWebControl.System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(String eventArgument)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges() 

在这种情况下如何删除记录?

非常感谢!

0 个答案:

没有答案