2013-03-01 138 views
-3

我在寫一個ASP.NET MVC 3應用程序。 我寫的與實體框架和LINQ ,但我對LINQ聲明將sql語句轉換爲linq;

  1. ,如果你有一個問題:

    select a, (select d from tabled where id = '12 ') as c from tableA inner join TableB on tablea.id = tableb.id 
    

    那麼如何(使用控制器切換到LINQ和與ViewBag分配。海峽= ...) (如何能在視圖中,可以顯示和c)

  2. ,如果他的說法是,例如:Product product = db.Product.Find (id) 那麼你怎麼了確定產品是否爲空?

回答

0
VAR

A =由在表A p加入中的q tableB的上p.id等於q.id選擇新的{P.A,從r在提交其中r.id == 12選擇r.d} .ToList();

這是該語句的LINQ查詢。此外

可以使用

Product product = db.Product.Find (id); 
if (product == null) return "Emplty"; 
+0

這是你的工作...請讓它作爲答案,如果它可以幫助你。 – 2013-03-01 05:02:04

+0

謝謝 ,如果我將它傳遞給1 ViewBag.str =從表p中的p連接q等於q.id選擇新的{pa,從r print tabled其中r.id == 12 select rd} 。 ToList(); 如何分隔每個字段(pa,rd)是從這個ViewBag.str! – 2013-03-01 07:17:44

+0

不可以添加查看包而不是你可以通過返回視圖(ans)返回這個查詢結果;那麼u cn很容易把視圖內的屬性 – 2013-03-01 07:19:22

0

你必須弗洛以下步驟; 1)在模型中作爲創建的返回值類:

public class ClassResult 
{ 
    public int a1 { get; set; } 
    public int b1 { get; set; } 
} 

則控制器

編寫查詢如下上:

public ActionResult Index() 
    { 
     List<TableAClass> ListA = new List<TableAClass>(); 
     List<TableBClass> ListB = new List<TableBClass>(); 
     List<TableCClass> ListC = new List<TableCClass>(); 

     List<ClassResult> res = new List<ClassResult>(); 

     res = (from p1 in ListA join p2 in ListB on p1.a1 equals p2.b1 select new ClassResult { a1=p1.a1 ,b1=p2.b1 }).ToList(); 

     return View(res); 
    } 

3)上的視圖,

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.ClassResult>" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
    <title>Index1</title> 
</head> 
<body> 
    <fieldset> 
     <legend>Fields</legend> 

     <div class="display-label">a1</div> 
     <div class="display-field"><%: Model.a1 %></div> 

     <div class="display-label">b1</div> 
     <div class="display-field"><%: Model.b1 %></div> 

    </fieldset> 


</body> 
</html>