powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / ADO.NET, LINQ, Entity Framework, NHibernate, DAL, ORM [игнор отключен] [закрыт для гостей] / Сортировка в Entity framework
15 сообщений из 15, страница 1 из 1
Сортировка в Entity framework
    #36037882
GraDea
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Всем привет!

Есть две таблицы, связанные один ко многим. Я добавил их в модель средствами VS

В коде я получаю экземпляр записи родительской таблицы, заполняю свойство-список дочерней и все это привязываю (Binding) в датагрид и прочие контролы в TwoWay режиме (используется wpf ). Это позволяет мне с минимумом кода и телодвижений иметь приложение для показа и редактирования данных.

Но есть ложка дегтя. Сортировка.

Сортировка записей дочерней таблицы по умолчанию меня не устраивает и она мне непонятна.
Если я
в ItemsSource отдаю список с методом MyList.OrderBy(...)
то невозможно редактирование.

Пытаюсь в модели написать
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
<EntitySet 
  Name="StudDiscipline" 
  EntityType="diplomModel.Store.StudDiscipline" 
  store:Type="Tables" 
  store:Schema="dbo" 
  store:Name="StudDiscipline">
  <DefiningQuery>SELECT 
     [id_discipline]
    ,[id_student]
    ,[Name]
    ,[Mark]
    ,[Hours]
    ,[OrderNumber]
    FROM [dbo].[StudDiscipline]
    ORDER BY [OrderNumber]
  </DefiningQuery>
</EntitySet>

но программа ругается

{"The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified."}

Контрол, который я использую (DataGrid из WPFToolbox) не поддерживает сортировку при работе с Entity Model и Linq2Sql

Подскажите как я могу выдать данные пользователю в нужном мне порядке при сохранении возможности редактирования!

Заранее спасибо!

С уважением,
Пешков Евгений.
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36037894
Фотография buser
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
бекоз лик оборачивает всю вашу конструкцию в скобочки и заталкивает во фром...?
он не такой умный? Зачем вам сдался ордер бай? указывайте через код порядок сортировки...
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36038535
SeVa
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Контролы WPF сами обеспечивают сортировку ICollectionView
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36053078
GraDea
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SeVa,
Как я понял таким образом я получу view без обратной связи?

Мне надо получить данные в грид, отсортированные как надо, с возможностью редактирования.

Как мне проще всего это сделать?


buserуказывайте через код порядок сортировки...

MyList.OrderBy(...) не работает так как мне надо.

Или имелось ввиду что-то другое?
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36053548
SeVa
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
При редактировании сортировку должен делать только контрол,в grid'e эта возможность есть.
Почитай для начала документацию
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36053549
SeVa
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
авторКак я понял таким образом я получу view без обратной связи?
И еще про ObservableCollection
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36054976
GraDea
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SeVa,
У Вас есть рабочий пример кода работы с ДатаГрид из WPFToolbox с сортировкой по нужному столбцу? Если есть, не могли бы Вы поделиться?

С уважением,
Пешков Евгений
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36054996
GraDea
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Нашел нечто подобное тому, что мне надо

http://blog.nicktown.info/2008/12/10/using-a-collectionviewsource-to-display-a-sorted-entitycollection.aspx

Пока разбираюсь.
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36055317
GraDea
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Вроде работает! Только почему-то один раз отрабатывает.

Я из тривью выбираю элемент, на основе выбора получаю элемент из Entity Model

private void TextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
TextBlock tbStudinTV = (TextBlock)sender;
Guid g = new Guid(tbStudinTV.Tag.ToString());
Student stud = (from student in dip.Student where student.ID_Student == g select student).First();
stud.StudDiscipline.Load();
base.DataContext = stud;
}

Когда я первый раз выбираю студента все дисциплины загружаются с сортировкой как надо. Но второй и последующие выборы выводят не сортированный список.
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36056181
SeVa
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Посмотрел ссылку,на мой взгляд, подход через одно место.Есть бесплатные гриды сторонних фирм,которые поддерживают сортировку без этих танцев с бубнами и дополнительными тормозами.
Поскольку только начинаешь, перейди на Silverlight, судя по всему, он идет в МС с более высоким приоритетом, чем WPF(грид впервые появился в нем).В SL для EF есть RIA Service.
Код,который ты привел в конце, выбрось и забудь.Binding WPF/SL позволяет полностью обходится без обработчиков клацанья мышкой.Примерный вариант возможного решения - MVVM
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36063745
GraDea
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SeVa,
То что лишний код, это конечно плохо и очень жаль, что дефолтный грид не поддерживает сортировку при работе с entity model. Будем надеяться, что ситуация исправиться, об этом баге известно.

Насчет MVVM и клацанья мышкой.
Что-то сразу об этом не подумал %). Остальное то все сделано именно через байдинги, а то что можно и DataContext передать - не сразу понял.

Только теперь проблема с отложенной загрузкой - пока не заполняются гриды, остальные поля заполняются.

огромное спасибо за помощь и советы!
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36064254
SeVa
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Только теперь проблема с отложенной загрузкой - пока не заполняются гриды, остальные поля заполняются.
]
Обычно в этом случае:
- в ViewModel или Model создают свойство IsBusy.Перед загрузкой его устанавливают в true, после - false
- в View добавляют всплывающий/перекрывающий BusyControl(погугли готовые реализации),его свойство Collapsed связывают с IsBusy с помощью BooleanToVisibilityConverter
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36064538
GraDea
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Я явно загружаю связанные списки в коде, ставлю брейкпоинт и вижу, что у связанных списков IsLoaded == true, но в ДатаГриде не вижу данных.
...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36064703
SeVa
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Так бы сразу и сказал

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
public class Student
{
   
   public ObservableCollection<Discipline> Disciplines
   { 
        get { return _desciplines ; } 
   }
   public LoadDisciplines()
   { 
     _desciplines.Clear();
     //код для загрузки
   }
}


public class StudentViewModel :  INotifyPropertyChanged
{
   private _model;
   private ICollectionView _desciplinesViewModel;


   public StudentViewModel()
   {
      _model = new Student();
      _desciplinesViewModel = new CollectionViewModel<Discipline>(_model.Disciplines);
   }

    // The View binds to the desciplines ViewModel through the ICollectionView interface.
        public ICollectionView Disciplines
        {
            get { return _desciplinesViewModel ; }
        }


       public LoadDisciplines()
       {
           IsBusy = true;
           _model.LoadDisciplines();
           IsBusy = false;
       }

CollectionViewModel поддерживает сортировку,группировку, фильтрацию

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
419.
420.
421.
422.
423.
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2008-2009 David Hill. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
///////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Microsoft.Practices.Composite.Presentation.Commands;

namespace Helix.Samples.CollectionViewModel
{
    /// <summary>
    /// A generic ViewModel that wraps an underlying collection model.
    /// </summary>
    /// <typeparam name="T">The type of the items in the underlying collection</typeparam>
    public class CollectionViewModel<T> : ObservableCollection<T>, ICollectionView where T : class
    {
        // The underlying model that we're providing a CollectionViewModel for.
        private IEnumerable<T> _model;

        public CollectionViewModel( IEnumerable<T> model )
        {
            // Set reference to the underlying model.
            _model = model;

            // If the underlying model supports it,
            // monitor the underlying model for changes.
            INotifyCollectionChanged incc = _model as INotifyCollectionChanged;
            if ( incc != null )
            {
                incc.CollectionChanged += new NotifyCollectionChangedEventHandler( OnModelChanged );
            }

            // Initialize the view.
            UpdateView();

            // Initialize the CollectionViewModel's built-in commands.
            SelectNextCommand     = new DelegateCommand<object>( SelectNext, CanSelectNext );
            SelectPreviousCommand = new DelegateCommand<object>( SelectPrevious, CanSelectPrevious );
            SortByCommand         = new DelegateCommand<string>( SortBy );
            GroupByCommand        = new DelegateCommand<string>( GroupBy );
        }

        private int _currentIndex = -1;
        private SortDescriptionCollection _sortDescriptions;
        private ObservableCollection<GroupDescription> _groupDescriptions;

        // This should really be Predicate<T> but the ICollectionView
        // interface defines the filter predicate with an object type parameter.
        private Predicate<object> _filter;

        #region ICollectionView Members

        public event EventHandler CurrentChanged;

        public event CurrentChangingEventHandler CurrentChanging;

        public bool Contains( object item )
        {
            return base.Contains( item as T );
        }

        public object CurrentItem
        {
            get { return _currentIndex == -1 ? null : this[ _currentIndex ]; }
        }

        public int CurrentPosition
        {
            get { return _currentIndex; }
        }

        public bool IsCurrentAfterLast
        {
            get { return _currentIndex >= this.Count; }
        }

        public bool IsCurrentBeforeFirst
        {
            get { return _currentIndex < 0; }
        }

        public bool IsEmpty
        {
            get { return this.Count == 0; }
        }

        public bool MoveCurrentTo( object item )
        {
            if ( this.Contains( item ) )
            {
                return UpdateCurrentIndex( this.IndexOf( item as T ) );
            }

            // If item is not in collection or is null, move to unselected state.
            return UpdateCurrentIndex( -1 );
        }

        public bool MoveCurrentToFirst()
        {
            return UpdateCurrentIndex( 0 );
        }

        public bool MoveCurrentToLast()
        {
            return UpdateCurrentIndex( this.Count - 1 );
        }

        public bool MoveCurrentToNext()
        {
            return UpdateCurrentIndex( _currentIndex + 1 );
        }

        public bool MoveCurrentToPosition( int position )
        {
            return UpdateCurrentIndex( position );
        }

        public bool MoveCurrentToPrevious()
        {
            return UpdateCurrentIndex( _currentIndex > 0 ? _currentIndex - 1 : _currentIndex );
        }

        public void Refresh()
        {
            UpdateCurrentIndex( -1 );
        }

        public IEnumerable SourceCollection
        {
            get { Debug.Assert( _model != null ); return _model as IEnumerable; }
        }

        public bool CanFilter
        {
            get { return true; }
        }

        public Predicate<object> Filter
        {
            get { return _filter; }
            set { _filter = value; UpdateView(); }
        }

        public bool CanSort
        {
            get { return true; }
        }

        public SortDescriptionCollection SortDescriptions
        {
            get
            {
                if ( _sortDescriptions == null )
                {
                    _sortDescriptions = new SortDescriptionCollection();

                    // Monitor sort description collection for any changes.
                    ((INotifyCollectionChanged)_sortDescriptions).CollectionChanged += ( sender, e ) => UpdateView();
                }
                return _sortDescriptions;
            }
        }

        public bool CanGroup
        {
            get { return true; }
        }

        public ObservableCollection<GroupDescription> GroupDescriptions
        {
            get
            {
                if ( _groupDescriptions == null )
                {
                    _groupDescriptions = new ObservableCollection<GroupDescription>();

                    // Monitor group description collection for any changes.
                    _groupDescriptions.CollectionChanged += ( sender, e ) => UpdateView();
                }
                return _groupDescriptions;
            }
        }

        public ReadOnlyObservableCollection<object> Groups
        {
            get { throw new NotImplementedException(); }
        }

        public IDisposable DeferRefresh()
        {
            throw new NotImplementedException();
        }

        public System.Globalization.CultureInfo Culture
        {
            get
            {
                return System.Globalization.CultureInfo.InvariantCulture;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        #endregion

        #region Commands - SelectNext, SelectPrevious, SortBy, GroupBy
        public DelegateCommand<object> SelectNextCommand { get; private set; }

        private bool CanSelectNext( object arg )
        {
            return ( _currentIndex < this.Count - 1 );
        }

        private void SelectNext( object obj )
        {
            MoveCurrentToNext();
        }

        public DelegateCommand<object> SelectPreviousCommand { get; private set; }
        private bool CanSelectPrevious( object arg )
        {
            return ( _currentIndex > 0 );
        }

        private void SelectPrevious( object obj )
        {
            MoveCurrentToPrevious();
        }

        public DelegateCommand<string> SortByCommand { get; private set; }

        private void SortBy( string property )
        {
            this.SortDescriptions.Clear();
            SortDescriptions.Add( new SortDescription( property, ListSortDirection.Ascending ) );
        }

        public DelegateCommand<string> GroupByCommand { get; private set; }

        private void GroupBy( string property )
        {
            this.GroupDescriptions.Clear();
            GroupDescriptions.Add( new PropertyGroupDescription( property ) );
        }
        #endregion

        private void UpdateView()
        {
            IQueryable<T> results = BuildQuery();

            base.Clear();

            foreach ( T item in results )
            {
                this.Add( item );
            }

            UpdateCurrentIndex( -1 );
        }

        private IQueryable<T> BuildQuery()
        {
            // Build up a dynamic query using Linq Expressions.
            IQueryable<T> query = _model.AsQueryable<T>();

            Expression viewExpression = query.Expression;

            // Start with the filter expression.
            if ( Filter != null )
            {
                Expression<Func<T, bool>> filterLambda = item => Filter( item );

                viewExpression = Expression.Call(
                    typeof( Queryable ),
                    "Where",
                    new Type[] { query.ElementType },   // TSource.
                    viewExpression,
                    filterLambda );
            }

            // Append the sorting expression(s).
            string sortMethodName = "OrderBy";
            foreach( SortDescription sort in SortDescriptions )
            {
                // Create local parameter for lambda - know your closures!
                string propertyName = sort.PropertyName;
                Expression<Func<T, object>> sortLambda = item => GetPropertyValue( item, propertyName );

                viewExpression = Expression.Call(
                    typeof( Queryable ),
                    sortMethodName + (sort.Direction == ListSortDirection.Ascending ? "" : "Descending"),
                    new Type[] { query.ElementType, typeof( object ) }, // TSource, TKey
                    viewExpression,
                    sortLambda );

                // Switch to ThenBy for subsequent sorting.
                sortMethodName = "ThenBy";
            }

            // Append the grouping expression(s).
            // TODO: Support nested grouping properly...
            foreach ( GroupDescription group in GroupDescriptions )
            {
                PropertyGroupDescription propGroup = group as PropertyGroupDescription;
                if (propGroup != null)
                {
                    // Create local parameter for lambda - know your closures!
                    string propertyName = propGroup.PropertyName;
                    Expression<Func<T, object>> groupLambda = item => GetPropertyValue( item, propertyName );

                    viewExpression = Expression.Call(
                    typeof( Queryable ),
                    "GroupBy",
                    new Type[] { query.ElementType, typeof( object ) }, // TSource, TKey
                    viewExpression,
                    groupLambda );

                    // Sort by the grouping key.
                    Expression<Func<IGrouping<object,T>, object>> sortLambda = g => g.Key;

                    viewExpression = Expression.Call(
                    typeof( Queryable ),
                    "OrderBy",
                    new Type[] { typeof(IGrouping<object,T>), typeof( object ) }, // TSource, TKey
                    viewExpression,
                    sortLambda );

                    // Flatten the groups using SelectMany.
                    Expression<Func<IGrouping<object, T>, IEnumerable<T>>> smLambda = g => g;

                    viewExpression = Expression.Call(
                    typeof( Queryable ),
                    "SelectMany",
                    new Type[] { typeof( IGrouping<object, T> ), query.ElementType }, // TSource, TResult
                    viewExpression,
                    smLambda );
                }
            }

            // Return the query.
            return query.Provider.CreateQuery<T>( viewExpression ); ;
        }

        private void OnModelChanged( object sender, NotifyCollectionChangedEventArgs args )
        {
            switch ( args.Action )
            {
                case NotifyCollectionChangedAction.Remove:
                    // If the removed item is in the current view, just remove it.
                    foreach ( T item in args.OldItems )
                    {
                        if ( base.Contains( item ) )
                        {
                            this.Remove( item );
                        }
                    }
                    break;
                case NotifyCollectionChangedAction.Add:
                case NotifyCollectionChangedAction.Replace:
                case NotifyCollectionChangedAction.Reset:
                    // Could optimize here, but just update the whole view for now...
                    UpdateView();
                    break;
            }
        }

        private object GetPropertyValue( T item, string propertyName )
        {
            PropertyInfo pi = item.GetType().GetProperty( propertyName );
            if ( pi != null )
            {
                return pi.GetValue( item, null );
            }
            return null;
        }

        private bool UpdateCurrentIndex( int index )
        {
            // Calculate new index bounded by -1 and the current collection size.
            int newIndex;
            newIndex = System.Math.Max( index, -1 );
            newIndex = System.Math.Min( newIndex, this.Count - 1 );

            if ( _currentIndex != newIndex )
            {
                if ( this.CurrentChanging != null )
                {
                    this.CurrentChanging( this, new CurrentChangingEventArgs( false ) );
                }

                _currentIndex = newIndex;

                if ( this.CurrentChanged != null )
                {
                    this.CurrentChanged( this, new EventArgs() );
                }

                OnPropertyChanged( new PropertyChangedEventArgs( "CurrentPosition" ) );
                OnPropertyChanged( new PropertyChangedEventArgs( "CurrentItem" ) );
                SelectNextCommand.RaiseCanExecuteChanged();
                SelectPreviousCommand.RaiseCanExecuteChanged();
            }

            return _currentIndex != -1;
        }
    }
}

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2008-2009 David Hill. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
///////////////////////////////////////////////////////////////////////////////
using System;
using System.ComponentModel;
using System.Reflection;

namespace Helix.Samples.CollectionViewModel
{
    public class PropertyGroupDescription : GroupDescription
    {
        public string PropertyName { get; private set; }

        public PropertyGroupDescription( string propertyName )
        {
            PropertyName = propertyName;
        }

        public override object GroupNameFromItem( object item, int level, System.Globalization.CultureInfo culture )
        {
            PropertyInfo pi = item.GetType().GetProperty( PropertyName );
            if ( pi != null )
            {
                return pi.GetValue( item, null );
            }
            return null;
        }
    }
}

...
Рейтинг: 0 / 0
Сортировка в Entity framework
    #36066143
GraDea
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Почти все заработало. Просто не там где надо указывал байдинг для датаконтекста, указывал в гриде, а надо было в Window.

Но вернулась старая проблема - единоразовая сортировка. При клике по студенту первый раз - все датагриды заполняются отсортировано, второй и последущие клики на других и этом студенте выводят несортированные данные (можно руками кликнуть по заголовку и отсортировать).

И я даже не знаю куда копать... Почему то, что работает один раз, не работает второй %) ???
...
Рейтинг: 0 / 0
15 сообщений из 15, страница 1 из 1
Форумы / ADO.NET, LINQ, Entity Framework, NHibernate, DAL, ORM [игнор отключен] [закрыт для гостей] / Сортировка в Entity framework
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]