S
S
SomeDeveloper2021-04-02 10:11:29
WPF
SomeDeveloper, 2021-04-02 10:11:29

Why can't I retrieve data from the WPF Entity database?

I'm trying to run the application, but an error pops up in the debugger related to "has no key defined"
I don't understand what it doesn't like, I tried to add [Key] in Role.cs, but this error still remains.
How can I fix what I wrote above?
I am using Entity Framework

Error
6066c3892231b066703770.jpeg

Table from DB
6066c39f7d493341041956.png

Role.cs

namespace MarathSkills
{
     class Role
    {        
        public char RoleId { get; set; }
        public string RoleName { get; set; }
    }
}


RoleContext.cs
using System.Data.Entity;
using System;

namespace MarathSkills
{
   class RoleContext : DbContext
    {
        public RoleContext() : base("DefaultConnection")
        {

        }
        public DbSet<Role> Roles { get; set; }
    }
}


TestD.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.Entity;

namespace MarathSkills
{
    /// <summary>
    /// Interaction logic for TestD.xaml
    /// </summary>
    ///

    public partial class TestD : Window
    {
        RoleContext db;
        public TestD()
        {
            InitializeComponent();
            db = new RoleContext();
            db.Roles.Load();
            phonesGrid.ItemsSource = db.Roles.Local.ToBindingList();

            this.Closing += Window_Closing;
        }

        private void phonesGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            db.Dispose();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sumor, 2021-04-04
@Sumor

It is better to use int type as id.
You can try to specify the Key for the hint.

[Key]
public char RoleId { get; set; }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question