Domanda

I'm building an MVC app and looking at translating the following simple SQL query

SELECT logon_count from application_users where username = 'username_to_find'

I'm new to LINQ and Entity Framework. I need to store the logon_count result as a C# int and only expect one result. A limit of 1 should probably be incorporated for safety.

The following class was automatically created from the database using ado.net and represents the application_users table.

public partial class application_users
{
    public int idapplication_users { get; set; }
    public string username { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public Nullable<int> logon_count { get; set; }
}

I also have the dbcontext

private thedbcontext dbcontext= new thedbcontext (); //In the controller

public partial class mycontext : thedbcontext 
{
    public virtual DbSet<application_users> application_users { get; set; }
}

Can someone suggest how I can better utilise LINQ/Entity Framework to execute the above SQL and obtain a result as a c# integer.

È stato utile?

Soluzione

Assuming that thedbcontext is a valid DbContext from EntityFramework, then all you need to do is the following

var usernameToFind = "user1";
var db = new mycontext();
var logonCount = db.application_users.Count(t => t.username == usernameToFind);

Typically your mycontext class would derive directly from EF's DbContext class like so

public partial class mycontext : DbContext
{
    public virtual DbSet<application_users> application_users { get; set; }
}

Altri suggerimenti

Like that:

string username = "test";
using(var dbContext = mycontext())
{

var LogonCount = (from application_users in dbContext.application_users
                  where application_users.username == username
                  select application_users).Count();
}

or you can use lambda expression like Richard posted.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top