开发者

C#, Linq data from EF troubles

I don't have much experience with programming. I am working (to learn) on a project. I am using C# 4.0 and WPF 4 with EF (SQLite). I am having problemw with LINQ.

Here is the code in question (I hope this is enough, let me know if more is needed)

        private void cboSelectCompany_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        using (ShippingEntities context = new ShippingEntities())
        {
            var companies = from company in context.Deliveries
                            where company.State == cboSelectCompany.SelectedItem.ToString()
                            select company;

            txtDeliveryName.Text = companies.Name;
            txtDeliveryState.Text = companies.State;
        }

The last two lines don't work. Am I misunderstanding what LINQ is returning? I just get this error

Error   5   'System.Linq.IQueryable<SqliteDemo.Delivery>' does not contain a definition for 'State' and no extension method 'State' accepting a first argument of type 'System.Linq.IQueryable<SqliteDemo.Delivery>' co开发者_运维问答uld be found (are you missing a using directive or an assembly reference?)   c:\users\dan\documents\visual studio 2010\Projects\SqliteDemo\SqliteDemo\DeliveryCompanies.xaml.cs  49  51  SqliteDemo

If anyone could give me some pointers or to a good reference I would appreciate it


You're close!

Linq is returning a Queryable set of Deliveries, which hasn't executed yet. My guess based on reading your code is that you're expecting at most one result, and then you want to put those values into a UI of some sort. In that case what you'll want to do is:

  1. Take your IQueryable and execute it
  2. Make sure you grab the first (or, alternatively enforce that there is only one) row
  3. Set the appropriate values in the UI.

So, leave the line with the query there, and then change the rest to something like this:

var company = companies.FirstOrDefault();
txtDeliveryName.Text = company.Name;
txtDeliveryState.Text = company.State;

Insert null-checking as appropriate, and go check out the differences between First, FirstOrDefault, Single, and SingleOrDefault to see which one seems most correct for your particular situation.


Well, looks like companies.State doesn't compile, because companies is a list of SqliteDemo.Delivery (and not just a SqliteDemo.Delivery).

What do you want to achieve? Imagine that your LINQ query returns several results, is it possible?


Just use companies.FirstOrDefault() or companies.Single() to access first item becouse by default LINQ returns collection of items not just single item.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜