简体   繁体   中英

Cannot convert type 'System.Linq.IQueryable<System.Guid>' to 'System.Guid' after runnig program

I'm new to C# and entity I was wondering if someone help me here. I have select which return my customerid so I want to pass it to my constructor as parameter,my constructor parameter type is guid but my select type is different , i don't know how I can convert it to guid. here is my code:

namespace FactorEntity
{
    public partial class CustomerResearchForm : MetroFramework.Forms.MetroForm
    {
        FactorEntities contex;
        MenuForm _customerform;

        void CResearchGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var CustomerUpdateAndDelete = 
                new CustomerUpdateAndDelete();
            contex = new FactorEntities();
            var sendergrid=(DataGridView)sender;
            var customercode =
            var cellValue =
               sendergrid.Rows[e.RowIndex].Cells[1].Value; 
            Convert.ToInt32(cellValue);
            var customer = from _customer in contex.tblCustomers
                           where _customer.CustomerCode==customercode
                           select _customer.CustomerID;
            var _CustomerId=(Guid)(customer);
            var customerform = 
                     new CustomerForm(_customerform,_CustomerId);                  
            customerform.Show();     
        }
    }
}

error is in this line : Guid _CustomerId=(Guid)(customer); thanks in advance.

The linq query its ok but the Where method return a IQueryableSystem type, its like a list of results. you must select the first result or change the query for change the return type to only 1 element.

I would change the linq query in this form to get the first element:

var customers = from _customer in contex.tblCustomers where
               _customer.CustomerCode==customercode select _customer.CustomerID;

var customer = customers.First();

Or Use this query for get only 1 element in case you know the query will produce only 1 element or it will throw an error:

var customer = contex.tblCustomers.Single(x => x.CustomerCode == customercode);

With

Guid _CustomerId=(Guid)(customer);

You're tying to get a list of elements from query and convert to a single element.

You have to get like:

 Guid _CustomerId=(Guid)(customer.First());

or better

 Guid _CustomerId=customer.FirstOrDefault() as Guid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM