1

Я работаю над приложением Silverlight 3 с услугами RIA. У меня приложение работает, но по какой-то причине оно только чтение данных, а не внесение изменений.Silverlight 3 + RIA Services Data Commit Issue

Большинство онлайн-примеров, которые я видел, используют Linq2Entities; мы используем Linq2SQL (наша модель данных довольно хорошо, как есть, без абстракции.)

Вот фрагмент службы:

[EnableClientAccess] 
public class FooService : LinqToSqlDomainService<FooDataContext> 
{ 
    [RequiresAuthentication()] 
    public IQueryable<UserProfile> GetUserProfiles() 
    { 
     return this.Context.UserProfiles; 
    } 

    [RequiresAuthentication()] 
    public void InsertUserProfile(UserProfile profile) 
    { 
     this.Context.UserProfiles.InsertOnSubmit(profile); 
    } 

    [RequiresAuthentication()] 
    public void UpdateUserProfile(UserProfile currentProfile) 
    { 
     this.Context.UserProfiles.Attach(currentProfile, true); 
    } 

    [RequiresAuthentication()] 
    public void DeleteUserProfile(UserProfile profile) 
    { 
     this.Context.UserProfiles.Attach(profile, profile); 
     this.Context.UserProfiles.DeleteOnSubmit(profile); 
    } 
} 

Вот отрывок из XAML, я использую:

<dataControls:DataForm x:Name="_profileForm" AutoGenerateFields="False" CommandButtonsVisibility="Commit" AutoEdit="True" > 
       <dataControls:DataForm.EditTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Vertical"> 
          <dataControls:DataField Label="Username"> 
           <TextBox Text="{Binding UserName, Mode=TwoWay}" /> 
          </dataControls:DataField> 

          <dataControls:DataField Label="First Name"> 
           <TextBox Text="{Binding FirstName, Mode=TwoWay}" /> 
          </dataControls:DataField> 

          <dataControls:DataField Label="Last Name"> 
           <TextBox Text="{Binding LastName, Mode=TwoWay}" /> 
          </dataControls:DataField> 

          <dataControls:DataField Label="Password"> 
           <PasswordBox Password="{Binding Password, Mode=TwoWay}"/> 
          </dataControls:DataField> 

          <!-- [Snip] --> 

          </dataControls:DataField> 
         </StackPanel> 
        </DataTemplate> 
       </dataControls:DataForm.EditTemplate> 
      </dataControls:DataForm> 

А вот отрывок из Silverlight страницы:

public partial class Profile : Page 
{ 
    private FooContext _dataContext; 

    public Profile() 
    { 
     InitializeComponent(); 
     this._dataContext = new FooContext(); 
    } 

    protected override void OnNavigatedTo(NavigationEventArgs e) 
    { 
     LoadOperation<UserProfile> loadOperation = this._dataContext.Load<UserProfile>(this._dataContext.GetUserProfilesQuery()); 
     loadOperation.Completed += new EventHandler(this.LoadOperation_Completed); 
    } 

    private void LoadOperation_Completed(object sender, EventArgs e) 
    { 
     // Bind the RIA data to the controls 
     LoadOperation<UserProfile> loadOperation = sender as LoadOperation<UserProfile>; 
     this._profileForm.EditEnded += new EventHandler<DataFormEditEndedEventArgs>(ProfileForm_EditEnded); 
     this._profileForm.ItemsSource = loadOperation.Entities; 
     this._profileForm.CurrentIndex = 0; 
    } 

    private void ProfileForm_EditEnded(object sender, DataFormEditEndedEventArgs e) 
    { 
     this._dataContext.SubmitChanges(); 
    } 

ответ

0

Спасибо всем за помощь! Я НАКОНЕЦ понял, что нужно, чтобы заставить это работать. Я точно не знаю, почему именно, но это решило проблему. Я изменил метод обновления к следующему:

[RequiresAuthentication()] 
public void UpdateUserProfile(UserProfile currentProfile) 
{ 
    UserProfile originalProfile = this.ChangeSet.GetOriginal(currentProfile); 
    this.Context.UserProfiles.Attach(currentProfile, originalProfile); 
} 

Уф. Теперь просто понять, почему он не смог подключить объект, прежде чем захватить его оригинальную версию.

Еще раз спасибо, очень ценим !!

+0

Может быть, связано с этим? http://blog.davidyack.com/journal/2009/7/21/ria-services-domaindatasourcedata-not-updating.html –

+0

Вы можете получить эту проблему, если есть несоответствие в ваших данных, в моем случае я было поле char (1) в базе данных, которое было нулевым, но в dataclasses было поле Nullable false – Martin

1

есть ошибка, ничего не делает случается, когда вы вызываете SubmitChanges?

Вот что я хотел бы попробовать:

  1. Установить точки останова на методах сервера CR, чтобы убедиться, что они называют.
  2. Убедитесь, что вы не передаете NULL для любого из значений, как that can cause a new instance to be created rather than an update of the existing entity.
  3. Я бы попытался добавить событие OnSubmitCompleted, чтобы проверить наличие ошибок. Пример кода (from this PDF):

    this._dataContext.SubmitChanges(OnSubmitCompleted, null); 
    
    private void OnSubmitCompleted(SubmitOperation so) 
    { 
         if (so.Error != null) 
         { 
           string message = so.Error.Message; 
           if (so.EntitiesInError.Any()) 
           { 
             message = string.Empty; 
             Entity entityInError = so.EntitiesInError.First(); 
             if (entityInError.Conflict != null) 
             { 
               EntityConflict conflict = entityInError.Conflict; 
               foreach (EntityConflictMember cm in 
                          conflict.MemberConflicts) 
               { 
                 message += string.Format( 
                   "Member '{0}' in conflict: Current: {1}, 
                         Original: {2}, Store: {3}", 
                   cm.PropertyName, cm.CurrentValue, 
                   cm.OriginalValue, cm.StoreValue); 
               } 
             } 
             else if (entityInError.ValidationErrors.Any()) 
             { 
               message += "\r\n" + 
                entityInError.ValidationErrors.First().Message; 
             } 
           } 
           MessageBox.Show(message, "Submit Failed", MessageBoxButton.OK); 
         } 
    } 
    
+0

1. Я установил точки останова и вызывает метод обновления. 2. Никаких нулей не передается (и никаких новых записей, отображаемых в БД.) 3. Добавлено это событие и т. Д. Error = null. Выход на клиент Silverlight выглядит нормально; Я даже добавил DataGrid, и он отражает изменения в форме данных. Я проверил следующее в сервисе, чтобы убедиться, что это не проблема с записью с БД, и он работает: var profile = (из профилей в Context.UserProfiles где profiles.DBPrimaryKey == 1 выбрать профили) .Первый(); profile.LastName = "Changed"; Контекст.Отправить изменения(); –

+0

Мой текущий подозреваемый - это метод UpdateUserProfile() службы домена, но я попробовал несколько изменений на нем без каких-либо изменений. Это называется, хотя, я это подтвердил. –

2

ли удаление [RequiresAuthentication] изменить поведение на всех?

Еще одна вещь, которую можно проверить, может быть конфигурационный файл - в частности, глаголы объявления HttpHandler (GET, POST).

(список сообщений чертов Meetup - Я ударил предел 3 сообщений в течение дня, как NEWB): P