简体   繁体   English

将Sql语句转换为Linq以与C#,实体框架,MVC3一起使用

[英]Convert Sql Statement into Linq for use with C#, Entity Framework, MVC3

I need to convert a sql statement to a linq query. 我需要将sql语句转换为linq查询。

The code below has my area in question marked - 下面的代码将我所关注的区域标记为-

public class MyObjectController : Controller
{
    private EFDbContext db = new EFDbContext();
    private IObjectRepository objRepo;

    public MyObjectController(IObjectRepository objectRepository)
    {
        objRepo = objectRepository;
    }

    //
    // GET: /Client/MyObject/

    public ActionResult Index()
    {
        if (User.Identity.IsAuthenticated)
        {
            MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true);

            if (currentUser != null && currentUser.ProviderUserKey != null && currentUser.IsApproved)
            {
                var currentUserId = (Guid)currentUser.ProviderUserKey;

<========HOW TO EXECUTE IN LINQ==================>
             Object result = (from obj in objRepo
                             where obj.ObjId == currentUserId
                             select obj).FirstOrDefault();
<========HOW TO EXECUTE IN LINQ==================>

             return View(result);
            }                
        }
        return View();

    }

Just to clarify - I am going for something more like this but I don't know how to get the syntax right: 只是为了澄清-我将继续这样,但我不知道如何正确使用语法:

Object myObj = moveRepo.Objects
                    .Where(m => m.ObjectId)
                    .Equals(m => currentUserId)
                return View(myObj);

You are using LINQ and I don't see any SQL statement. 您正在使用LINQ,但没有看到任何SQL语句。 Probably you want to modify the LINQ statement to work it properly. 可能您想修改LINQ语句以使其正常工作。 In your query you need to specify the data context and the table. 在查询中,您需要指定数据上下文和表。

var result = (from obj in yourDataContext.yourEntity
             where obj.ObjId == currentUserId
             select obj).FirstOrDefault();

That query will give you your record if found, null otherwise 该查询将为您提供记录(如果找到),否则返回null

Have a look at LINQpad . 看看LINQpad

I've found it to be really useful and is ideal for checking what if your linq is doing what you are used to with SQL. 我发现它非常有用,非常适合检查linq是否正在执行SQL的常规操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM