This is a migrated thread and some comments may be shown as answers.

Binding to Grid with Entity Framework 4.1 Codefirst

7 Answers 216 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Reinhard
Top achievements
Rank 2
Reinhard asked on 16 Jun 2011, 04:42 PM
Hello all.

I have updated my Entity Framework 4.0 to 4.1Since i have a problem with the binding to Radgridview control.

My Dataclasses as sample:
namespace KfzOrtung6DataClasses.Modells
{
    public class Fahrzeuge
    {
         
        public Fahrzeuge()
        {
            this.FahrzeugPositionen = new ObservableCollection<Positionen>();
        }
 
        [Required]
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public Guid ID { get; set; }
 
        [Required]
        [MaxLength(50)]
        public string Name { get; set; }
 
        [Required]
        [MaxLength(50)]
        public string Kennzeichen { get; set; }
 
        public string Rufnummer { get; set; }
         
        public int Aktiv { get; set; }
        public DateTime Ablaufsimkarte { get; set; }
 
        [MaxLength(4000)]
        public string Bemerkung { get; set; }
 
        public virtual ObservableCollection<Positionen> FahrzeugPositionen { get; private set; }
    }
}



In my UC i have into the Loaded-Event:
this.DataContext = this.ItemsSource;

The Collectionview Method:
ICollectionView _itemsSource;
public ICollectionView ItemsSource
{
    get
    {
        if (_itemsSource == null)
        {
            using (var ktt = new KfzContext6())
            {
                ktt.MFahrzeuge.Load();
                var c = ktt.MFahrzeuge.Local.ToBindingList();
                var collectionViewSource = new CollectionViewSource {Source = c};
                _itemsSource = collectionViewSource.View;
            }
        }
        return _itemsSource;
    }
    set
    {
        _itemsSource = value;
        OnPropertyChanged("ItemsSource");
    }
}
#endregion

In my context class:
namespace KfzOrtung6DataClasses.Modells
{
    public class KfzContext6 : DbContext
    {
        public KfzContext6(): base("KfzContext6")
        {
            
        }
         
        public DbSet<Fahrzeuge> MFahrzeuge { get; set; }
        public DbSet<Positionen> MPositionen { get; set; }
        public DbSet<Tarife> MTarife { get; set; }
        public DbSet<Benutzer> MBenutzer { get; set; }
        public DbSet<SmsProtokoll> MSmsProtokoll { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            // Hier können manuelle Änderungen an Datenbank vorgenommen werden!!
            //Beispiel:
            //modelBuilder.Entity<Benutzer>().Property(r => r.ID).HasColumnName("Id");
        }
 
    }
}

My save method:
selectedFahrzeugAusListe.Aktiv = chkFahrzeugAktiv.IsChecked == true ? 1 : 0;
selectedFahrzeugAusListe.Rufnummer = txFahrzeugGpsnummer.Text.Trim();
selectedFahrzeugAusListe.Kennzeichen = txFahrzeugKennzeichen.Text.Trim();
selectedFahrzeugAusListe.Bemerkung = txFahrzeugKommentar.Text.Trim();
selectedFahrzeugAusListe.Name = txFahrzeugName.Text.Trim();
selectedFahrzeugAusListe.Ablaufsimkarte = dateTimePicker.DisplayDate;
 
using (var ktt = new KfzContext6())
{
    ktt.MFahrzeuge.Add(selectedFahrzeugAusListe);
    ktt.SaveChanges();
    ItemsSource.Refresh();
}

In xaml of the radgridview:
<telerik:RadGridView AutoGenerateColumns="False"
                     CanUserFreezeColumns="False"
                     CanUserResizeColumns="True"
                     Margin="10,6,10,13"
                     x:Name="FahrzeugGrid"
                     RowIndicatorVisibility="Visible"
                     AutoExpandGroups="True"
                     IsFilteringAllowed="False"
                     ShowGroupPanel="False"
                     ShowGroupFooters="False"
                     IsReadOnly="True"
                     SelectionChanged="FahrzeugGrid_SelectionChanged"
                     ActionOnLostFocus="None"
                     AreRowDetailsFrozen="True"
                     CanUserInsertRows="False"
                     CanUserDeleteRows="False"
                     RowDetailsVisibilityMode="Visible" Grid.Row="1"
                     ItemsSource="{Binding ItemsSource, ElementName=DataSourceChangeNotificationsFahrzeugControl}"
                     DataLoaded="FahrzeugGrid_DataLoaded" >
 
    <telerik:RadGridView.ParentRow>
        <telerik:GridViewRow IsTabStop="False" />
    </telerik:RadGridView.ParentRow>
     
    <telerik:RadGridView.Columns>
        <telerik:GridViewDataColumn DataMemberBinding="{Binding Name}"
                                    Header="Fahrzeugname" Width="200" />
 
        <telerik:GridViewDataColumn DataMemberBinding="{Binding Kennzeichen}"
                                    Header="Kennzeichen" Width="140" />
 
        <telerik:GridViewColumn Header="Aktiv" Width="40" IsFilterable="True">
            <telerik:GridViewColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsEnabled="False"
                              IsChecked="{Binding Path=Aktiv, Converter={StaticResource CopnvertIntToBool1} }">
                    </CheckBox>
                </DataTemplate>
            </telerik:GridViewColumn.CellTemplate>
        </telerik:GridViewColumn>
 
        <telerik:GridViewDataColumn
            DataMemberBinding="{Binding Rufnummer}"
            Header="GPS Nummer" Width="150" />
 
        <telerik:GridViewDataColumn
            DataMemberBinding="{Binding Ablaufsimkarte}"
            Header="Ablauf Karte" Width="90" />
 
        <telerik:GridViewDataColumn
            DataMemberBinding="{Binding Bemerkung}"
            Header="Kommentar" Width="*" />
 
    </telerik:RadGridView.Columns>
</telerik:RadGridView>

It shows all cars, but when i save a new car, the list doesn´t refresh.
When i reload the UC, then all cars (the new one too) are all there.

Can you please help?

Reinhard

7 Answers, 1 is accepted

Sort by
0
Reinhard
Top achievements
Rank 2
answered on 18 Jun 2011, 02:40 PM
Hello again.

I I had uploaded a short video less then 3 minutes, that shows my problem in detail.

Hope anyone can halp.
Reinhard
0
Rossen Hristov
Telerik team
answered on 22 Jun 2011, 08:16 AM
Hi Reinhard,

We would really like to help you.

We watched the video, but we really can't figure out why is this happening without having something that we can debug. Would it be possible to to the following.

Could you prepare an extremely dummy sample project that mimics the architecture of your real one. It can use a brand new dummy database with 1 table or the popular databases such as AdventureWorkds, Northwind or Chinook, which we have. The dummy project should only have RadGridView and the button that you clicked in the video. This dummy project should reproduce the behavior that you are faced with in your real one. Once we have this dummy project we will immediately debug it in order to try to see why is the item there, but invisible.

Of course if your real project is not secret and you can make it compulable and runnable in a zip file, we could check it out as well. The ideas is that we should unzip it and be able to hit F5 and run it on our machines, so if there is stuff like third-party assemblies and databases that could be a problem.

Do you think that this approach would be possible?

We are looking forward to hearing from you.

Regards,
Ross
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Reinhard
Top achievements
Rank 2
answered on 27 Jun 2011, 09:39 AM
Hello and thanks for your answer.

Here is the DummyProject for testing.

Reinhard
0
Rossen Hristov
Telerik team
answered on 27 Jun 2011, 10:05 AM
Hi Reinhard,

Here is what I get when I run your project:

Cannot open database \"KfzContext6\" requested by the login.

Can you please send me a project that I can actually run and see stuff? Unless I have something that I can debug I am afraid that I cannot be of great help.

Your sample project can use a brand new dummy database with 1 table or the popular Microsoft sample databases such as AdventureWorks, Northwind or Chinook, which we have. It is the idea that is important here -- not the actual data.

I am looking forward to hearing from you. And to a runnable sample project.

Best wishes,

Ross
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Reinhard
Top achievements
Rank 2
answered on 27 Jun 2011, 11:46 AM
Hello.

Now it should work.
The entity framework 4.1 code first has been integrated.
This has the advantage that the framework takes care of itself about whether the database exists or not.
If the database does not exist, it is automatically created (in sqlexpress instance)

Please try it agein HERE DOWNLOAD

Reinhard
0
Rossen Hristov
Telerik team
answered on 27 Jun 2011, 02:05 PM
Hi Reinhard,

I updated the project with our latest binaries and ran it.

1. If you want to scroll to the newly added item, setting it as the Selected and CurrentItem is not relevant. There is not rule saying that the SelectedItem will always be on the screen. You have to tell the grid to scroll to the item like this:

Random random = new Random();
var r  = random.Next(1, 1000);
 
Fahrzeuge fz = new Fahrzeuge { ID = Guid.NewGuid(), Name = "Car" + r.ToString(), Ablaufsimkarte = new DateTime(2011, 1, 1), Kennzeichen = "SAD-TT-" + r.ToString() };
_kt.Fahrzeuges.Add(fz);
_kt.SaveChanges();
 
var tc = _kt.Fahrzeuges.Find(fz.ID);
 
FahrzeugGrid.SelectedItem = tc;
FahrzeugGrid.CurrentItem = tc;
 
FahrzeugGrid.ScrollIntoViewAsync(tc, null);

2. Regarding the sorting.

I have noticed that you have set IsCustomSortingEnabled=True and then you have not done absolutely anything to handle the custom sorting. You have to do the sorting yourself in case you set IsCustomSortingEnabled. I am not sure where did you see this property from, but this help article explains what it does and what do you need to do in order to handle the custom sorting.

I am almost sure that you do not really need custom sorting.
 
In case you do not want to perform custom sorting and you want the column to handle this for you, you will have set its DataMemberBinding. A column needs to have a DataMemberBinding so it knows which property it is bound to. In your project all of your columns are unbound and use CellTemplates -- that is why they cannot perform sorting out-of-the-box.

In your project, I have modified the Fahrzeugname column to use a DataMemberBinding and thus RadGridView's built-in sorting:

<telerik:GridViewDataColumn Header="Fahrzeugname"
                            Width="200"
                            DataMemberBinding="{Binding Name}"
                            IsCustomSortingEnabled="False">
    <telerik:GridViewDataColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Name}"
                       Width="200"
                       Background="Red"
                       IsEnabled="False"></TextBlock>
        </DataTemplate>
    </telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>

You can make all other columns like it if you want to.
 
Finally, my suggestion is to turn the Asynchronous mode off. It can cause a lot of trouble. We are actively trying to obsolete it, since when it was created RadGridView was very different from what it is now and there are certain scenarios in which this mode will not work correctly. That is my personal advise.

The binaries that I am using in the modified project should be released today with our Latest Internal Build. You can upgrade to them if you want.

I have attached the modified project.

I hope this helps.

Best wishes,
Ross
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Reinhard
Top achievements
Rank 2
answered on 27 Jun 2011, 07:52 PM
Hi,

Thank you for your great help!

Reinhard
Tags
GridView
Asked by
Reinhard
Top achievements
Rank 2
Answers by
Reinhard
Top achievements
Rank 2
Rossen Hristov
Telerik team
Share this question
or