2011-10-18 246 views
0

您好我已經通過遵循教程在Silverlight中創建了示例數據庫應用程序。我試圖在數據庫中插入一條記錄,但它會引發錯誤提交操作失敗驗證。請檢查EntitiesInError中Entity.ValidationErrors以獲取更多信息。我正在使用DAL的實體框架。我的代碼如下。插入記錄時發生異常。但Iam不確定在哪個階段發生異常。 RecordInsertPage.cs文件Silverlight 4 RIA服務問題

public partial class BookRegistaeration : ChildWindow 
    { 
     public Book newBook { get; set; } 
     public BookRegistaeration() 
     { 
      InitializeComponent(); 
      newBook = new Book(); 
      AddBookForm.CurrentItem =AddBookForm; 
      AddBookForm.BeginEdit(); 
     } 

    private void OKButton_Click(object sender, RoutedEventArgs e) 
    { 
     AddBookForm.CommitEdit(); 
     this.DialogResult = true; 

    } 

    private void CancelButton_Click(object sender, RoutedEventArgs e) 
    { 
     newBook = null; 
     AddBookForm.CancelEdit(); 
     this.DialogResult = false; 

    } 
} 

Service.cs頁

public class OrganizationService : LinqToEntitiesDomainService<LibraryEntities1> 
    { 

    public IQueryable<Book> GetBooks() 
    { 
     return this.ObjectContext.Books.OrderBy(e => e.BookId); 
    } 

    public void InsertBook(Book book) 
    { 
     //book.Title = "Hello book"; 
     //book.Author = "Ali"; 
     //book.Category = "Humanity"; 

      if ((book.EntityState != EntityState.Detached)) 
      { 
       this.ObjectContext.ObjectStateManager.ChangeObjectState(book, EntityState.Added); 
      } 
      else 
      { 
       this.ObjectContext.Books.AddObject(book); 
      } 


    } 

    public void UpdateBook(Book currentBook) 
    { 
     this.ObjectContext.Books.AttachAsModified(currentBook, this.ChangeSet.GetOriginal(currentBook)); 
    } 

    public void DeleteBook(Book book) 
    { 
     if ((book.EntityState != EntityState.Detached)) 
     { 
      this.ObjectContext.ObjectStateManager.ChangeObjectState(book, EntityState.Deleted); 
     } 
     else 
     { 
      this.ObjectContext.Books.Attach(book); 
      this.ObjectContext.Books.DeleteObject(book); 
     } 
    } 
} 



private void LibraryDataSource_SubmittedChanges(object sender, SubmittedChangesEventArgs e) 
     { 
      if (e.HasError) 
      { 
       MessageBox.Show(string.Format("Changes were not saved: {0}", e.Error.Message)); 
       e.MarkErrorAsHandled(); 
      } 
      submitButton.IsEnabled = true; 

     } 
    void addBook_Closed(object sender, EventArgs e) 
    { 
     BookRegistaeration book = (BookRegistaeration)sender; 
     if (book.newBook != null) 
     { 
      OrganizationContext _OrganizationContext = (OrganizationContext)(LibraryDataSource.DomainContext); 
      _OrganizationContext.Books.Add(book.newBook); 
      LibraryDataSource.SubmitChanges(); 
     } 
    } 

回答

0

嘗試做的異常消息表明,將斷點您SubmittedChanges事件,用來檢查異常對象,你應該能夠爲其請參閱EntitiesInError中每個實體的Entity.ValidationErrors。

這應該告訴你你試圖添加的對象中的哪個字段沒有通過驗證檢查,你可能在不能爲null的字段中有空數據。您可能會發現字符串屬性不允許爲空。

也試着確保表單正確填充要添加的對象,可以在調用CommitEdit之前放置一個斷點並檢查對象狀態。

0

我不明白這一行!

AddBookForm.CurrentItem = AddBookForm;

你爲什麼寫這個?

它應該是這樣的

AddBookForm.CurrentItem =你的類的對象!