Search code examples
asp.net-mvc-4entity-framework-4entity-framework-6

How do I get the Id of a user given the email address in ASP.NET MVC Entity Framework


I have user information in my database. I wish to get the ID of a user given the email address. To get this in sql you would write the following query code:

SELECT Id FROM TableName WHERE email_address = "xyz@somename.com";

How do I write this using ASP.NET MVC Entity-Framework?


Solution

  • Well, it depends entirely on your public API, which we have no visibility into. Generally speaking, it would look something like:

    var userId = db.Users
        .Where(m => m.email_address == "xyz@somename.com")
        .Select(m => m.Id)
        .SingleOrDefault();
    

    I suggest you take some time with the tutorials at https://www.asp.net/mvc/overview/models-data, to get your bearings.