将SQL转换/转换为实体框架/ LINQ

时间:2014-04-23 04:32:04

标签: c# sql linq entity-framework-5 asp.net-mvc-5

我正在构建一个MVC应用程序,并正在寻找翻译以下简单的SQL查询

SELECT logon_count from application_users where username = 'username_to_find'

我是LINQ和Entity Framework的新手。 我需要将logon_count结果存储为C#int,并且只需要一个结果。为安全起见,可能应加入限制1。

使用ado.net从数据库自动创建以下类,并表示application_users表。

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; }
}

我也有dbcontext

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

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

有人可以建议我如何更好地利用LINQ / Entity Framework来执行上述SQL并获得结果作为c#整数。

2 个答案:

答案 0 :(得分:3)

假设thedbcontext是来自EntityFramework的有效DbContext,那么您需要做的就是以下内容

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

通常,您的mycontext课程会直接来自EF的DbContext课程

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

答案 1 :(得分:1)

就像那样:

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();
}

或者您可以像Richard发布的那样使用lambda表达式。

相关问题