2012-06-28 36 views
0

我需要將sql語句轉換爲linq查詢。將Sql語句轉換爲Linq以用於C#,實體框架,MVC3

下面有我的問題區域標記的代碼 -

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

    } 

只是爲了澄清 - 我要更多的東西像這樣的,但我不知道怎麼弄的語法正確:

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

什麼? **是** LINQ。 –

+0

您是先使用edmx還是代碼? –

+0

我先使用代碼 –

回答

2

你正在使用LINQ,我沒有看到任何SQL語句。可能你想修改LINQ語句來正確工作。在你的查詢中,你需要指定數據上下文和表。

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

該查詢會給你你的記錄,如果發現了,否則返回null

+0

愚蠢的我。你可以知道我在LINQ中有多熟練......大聲笑。 –

+0

你熟悉這個錯誤 - 你熟悉這個錯誤 傳遞到字典的模型產品類型「System.Data.Entity.DynamicProxies.Object_3E186F803589BF82895B10E08C2A9AB68EFA619599418D6EB96585D14874CDC0」的,但這種字典需要類型的模型項目「系統.Collections.Generic.IEnumerable'1 [MySite.Domain.Entities.Object]」。 –

+0

@HelloJonnyOh,你可以檢查這個線程http://stackoverflow.com/questions/7392022/razor-proxy-type-error-system-data-entity-dynamicproxies或發佈一個新的問題與完整的場景 – Habib

1

看一看LINQpad

我發現它非常有用,並且非常適合檢查你的linq是否正在做你習慣的SQL。

+0

這是一個很棒的鏈接!謝謝......我只能感到遺憾的是我必須回答上面的實際答案(如此相互矛盾)。但是,謝謝你提及我。 (: –

+0

你熟悉這個錯誤 傳遞到字典的類型是「System.Data.Entity.DynamicProxies.Object_3E186F803589BF82895B10E08C2A9AB68EFA619599418D6EB96585D14874CDC0」的模型項目,但本詞典需要類型的「典範項目System.Collections.Generic.IEnumerable' 1 [MySite.Domain.Entities.Object]」。 –