Adding new items via Grid using RadEntityFrameworkCoreDataSource and MVVM

1 Answer 20 Views
GridView
Lee
Top achievements
Rank 1
Veteran
Lee asked on 23 Dec 2022, 06:59 PM | edited on 23 Dec 2022, 07:02 PM

Hello,

I followed setting up a RadGridView using a RadEntityFrameworkCoreDataSource using the MVVM approach outlined here.

This worked as expected for loading the data just fine. However, when I enabled the grid's CanUserInsertRow parameter, and try to add a row via the grid, I immediately get an exception from the AddingNewDataItem event stating that it cannot track the Entity of type <whatever> due to the primary key property being null. This would make sense to me if it were trying to commit the new row to the data source, but that would be after the user has a chance to enter the field information.

I understand there's an opportunity to set default values for these entities, however I wanted the user to input information themselves first, instead of setting up a valid row.

Previously, I have used DataTables/Views as a grid's item source with no problems, was able to capture exceptions thrown by the database in the UI itself and display them to the user.

Is this approach simply not suited for the Entity Framework data source? Or am I not familiar enough with this and MVVM, and should get myself caught up before continuing on?

Thanks for any help or suggestions,

Lee

 

1 Answer, 1 is accepted

Sort by
0
Stenly
Telerik team
answered on 27 Dec 2022, 04:43 PM

Hello Lee,

I was able to reproduce this exception in a sample project on my end. The reason for it is that the property that is specified as a primary key does not have a default value when adding a new instance of the object (clicking on the GridViewNewRow adds a new instance of the object before the user commits it). Since the default value of the string type is null, this exception is raised.

As mentioned that it is undesired to have a default value that the user has to remove and then insert the new one, this default value could be set to an empty string instead (as I think that the property that is specified as the primary key is of type string). This way, the exception will not be raised as the default value is no longer null.

The following code snippet shows this suggestion's implementation:

public class Person
{
    public Person()
    {

    }

    [Key]
    public string Name { get; set; } = "";
}

When adding a new entry via the GridViewNewRow element, the exception is no longer raised:

With this being said, could you give this suggestion a try?

Regards,
Stenly
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
GridView
Asked by
Lee
Top achievements
Rank 1
Veteran
Answers by
Stenly
Telerik team
Share this question
or