简体   繁体   中英

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

I need to convert a sql statement to a linq query.

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. Probably you want to modify the LINQ statement to work it properly. 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

Have a look at 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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