DataBinding () does not work with Distinct () (Entity Framework)

I would like to create an application that reads data from a database and then shows it through the user interface. Then the user can add / delete / update the fields and save them in the database, pretty standard, right?

I have two tables: Motors and Measures. The Motors table has many fields, one of which is the company. Of course, there can be several motors in one company, so I would like to filter out these companies and get only individual ones in comboBox.

I still play with the language and VS, so I made a simple version of the user interface where the user can add a new engine, in fact the user can add a company field, because I'm trying to add a new company and see if it will automatically update in comboBox .

For this purpose I use Entity Framework and this tutorial from msdn to bind data:

https://msdn.microsoft.com/en-us/data/jj682076.aspx

The problem is that when I add a new engine (with a new company), it does not update, if I filter individual ones, I mean that the following code works and automatically updates comboBox with all companies:

        private void MainForm_Load(object sender, EventArgs e)
    {
        _context = new MotorsContext();
        _context.Motors.Load();

        this.companyBindingSource.DataSource = _context.companies.ToBindingList();
        companyBindingSource.ListChanged += CompanyBindingSource_ListChanged;
    }

And the next one is not :

private void MainForm_Load(object sender, EventArgs e)
{
    _context = new MotorsContext();
    _context.Motors.Load();

    this.companyBindingSource.DataSource = _context.Motors.Local.ToBindingList().Select(x => x.company).Distinct();
    companyBindingSource.ListChanged += CompanyBindingSource_ListChanged;
}

ListChanged, , , . , . , ?

private void CompanyBindingSource_ListChanged(object sender, ListChangedEventArgs e)
{
    MessageBox.Show("List changed!");
}

, , :

private void button1_Click_1(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(textBox1.Text))
    {
        Motor m = new Motor();
        m.company = textBox1.Text;
        _context.Motors.Add(m);
        _context.SaveChanges();
        MessageBox.Show($"New motor, id: {m.motorID}");
    }
}

comboBox ( ):

→ " !". popup → " : id" popup

:

→ " : id"

, .

. , .

+4
2

:

_context.Motors.Local.ToBindingList().Select(x => x.company).Distinct();

, .Select(x => x.company).Distinct() BindingList<Motor>, IEnumerable<string>

:

var _companies = _context.Motors.Select(x => x.company).Distinct().ToList();

this.companyBindingSource.DataSource = _companies;
+2

this.companyBindingSource.DataSource = _context.Motors.Local.ToBindingList().Select(x => x.company).Distinct();

IEnumerable<T>. , , .ToList();

this.companyBindingSource.DataSource = _context.Motors.Local.ToBindingList().Select(x => x.company).Distinct().ToList();
0

All Articles