Search code examples
c#databaseentity-framework-6linq-to-entities

How can i get Id item number in entity data model


i'm trying to check the login information ,,, and get the item Id if they are correct ,,, Otherwise show error entry message my code is:

var getid = from user in db.tables
            where user.name == tbusername.Text && user.password == tbpassword.Text
            select user.Id;

c = Int32.Parse(getid);

but the vs say there's an error at c = Int32.Parse(getid); What's wrong?


Solution

  • You cant convert a list to an integer. Where returns a collection, (or said better an IEnumerable). You are pushing a list of something into a space (Int32.Parse) that only wants a 1 of something.

    Also if your Id is an int, you shouldn't have to parse it

    Example

    var getid = (from user in db.tables
                where user.name == tbusername.Text && user.password == tbpassword.Text
                select user.Id).FirstOrDefault();
    
    // or
    var getid = db.tables.Where(user => user.name == tbusername.Text && user.password == tbpassword.Text)
                         .Select(user => user.Id)
                         .FirstOrDefault();
    
    if(getid == null)
    {
        MessageBox.Show("Oh nooez!!!");
        return;
    }
    
    MessageBox.Show("You is id : " + getid );
    

    Enumerable.FirstOrDefault Method (IEnumerable)

    Returns the first element of a sequence, or a default value if the sequence contains no elements.

    Enumerable.Where Method (IEnumerable, Func)

    Filters a sequence of values based on a predicate.

    Return Value

    Type: System.Collections.Generic.IEnumerable An IEnumerable that contains elements from the input sequence that satisfy the condition.