How can I find a object from dbcontext with string parameter, not with Find(primary key) function

asp.net-mvc c# dbcontext entity-framework

Question

Yes, context.Accounts.Find(id) where id is primary key, it does bring me the right account. But I want to search from context.Accounts with string username, not by primary key.

To be more precise, method:

public void Authenticate(string username, password)
{       result = false;
        Accounts test = new Accounts();
        test.User = username;
        Accounts dbEntry = new Accounts();
        dbEntry = context.Accounts_.Find(test.User);

        if (dbEntry.Password == password)
            if(dbEntry.Admin == 1)
              result = true;
        return result;
    }

So username is not primary key anymore, how i can find the right one without Find() function?

1
1
7/16/2013 10:20:17 PM

Accepted Answer

replace

    Accounts test = new Accounts();
    test.User = username;
    Accounts dbEntry = new Accounts();
    dbEntry = context.Accounts_.Find(test.User); 

with

var dbEntry = context.Accounts_.FirstOrDefault(acc => acc.username == username);

or whatever the 'Username' is called in your Accounts_

3
7/16/2013 5:12:06 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow