2012-12-10 42 views
0

我正在顯示來自我的數據庫的記錄。該記錄從其他表中提取數據並在主表中使用Int來表示值,因此Item表的Division等於1,Division表1 = ALL。現在,我正在顯示記錄,我正試圖將1變成全部。所有ID字段都顯示int。這是我的代碼告訴它做的。但我試圖顯示名稱,當我這樣做時,我得到了很多紅色。它找不到名稱。 CatagoryID應該是CategoryNameLinq按主鍵查找項目並顯示名稱(位於不同的表中)

希望是有道理的。

if (!IsPostBack) 
{ 
    string v = Request.QueryString["ContactID"]; 
    int itemid; 
    int.TryParse(v, out itemid); 
    var customerInfo = GetCustomerInfo(itemid); 
    CONTACTID.Text = customerInfo[0].ContactID.ToString(); 
    ContactTitle.Text = customerInfo[0].ContactTitlesID.ToString(); 
    ContactNameB.Text = customerInfo[0].ContactName; 
    DropDownAddCategory.Text = customerInfo[0].CategoryID.ToString(); 
    DDLAddDivision.Text = customerInfo[0].DivisionID.ToString(); 
    ContactPhoneBox.Text = customerInfo[0].ContactOPhone; 
    ContactCellBox.Text = customerInfo[0].ContactCell; 
    ContactEmailBox.Text = customerInfo[0].ContactEmail; 
    CextB.Text = customerInfo[0].Ext; 
} 

private List<Solutions.Models.Contact> GetCustomerInfo(int itemid) 
{ 
    using (ItemContext context = new ItemContext()) 
    { 
     return (from c in context.Contacts 
       where c.ContactID == itemid 
       select c).ToList(); 
    } 
} 

這是你使用LINQ to SQL或實體框架模型

public class Contact 
{ 
     [ScaffoldColumn(false)] 
     public int ContactID { get; set; }  
     public System.DateTime ContactCreated { get; set; }  
     public string ContactName { get; set; }  
     public int? ContactTitlesID { get; set; }  
     public string ContactOPhone { get; set; }  
     public bool cApproved { get; set; }  
     public string User { get; set; } 
     public string ContactCell { get; set; }  
     public string ContactEmail { get; set; }  
     public int? DivisionID { get; set; }  
     public int? CategoryID { get; set; }  
     [StringLength(5)] 
     public string CExt { get; set; }   
     public virtual Division Division { get; set; } 
     public virtual Category Category { get; set; } 
     public virtual ContactTitle ContactTitle { get; set; }  
     public string Ext { get; set; } 
} 
+0

你會需要充實這一點位。 '得到很多紅色'並不能幫助我們回答你的問題。此外,試圖顯示名稱...在哪裏? – Alex

+0

它不是從其他表中抓取數據以便拉取我正在尋找的CategoryName。它只顯示當前表格的值。在這種情況下,'context.Contacts'是唯一可以顯示的數據。 – jackncoke

+0

你的貼圖是什麼樣的?我假設你正在使用LINQ到SQL? – Alex

回答

1

實體框架,你可以include相關實體在查詢結果:

與產品類別的對象
return (from c in context.Contacts.Include("Catagory") 
     where c.ContactID == itemid 
     select c).ToList(); 

這將返回聯繫人:customerInfo.Catagory.CategoryName

BTW而不是返回的聯繫人列表,並選擇由第一個索引(因此可能索引超出範圍例外),修改您的方法返回第一個聯繫人(或默認,如果未找到):

private Solutions.Models.Contact GetCustomerInfo(int itemid) 
{ 
    return (from c in context.Contacts.Include("Catagory") 
      where c.ContactID == itemid 
      select c).FirstOrDefault(); 
} 

而且使用這種方式:

var customerInfo = GetCustomerInfo(itemid); 
if (customerInfo != null) 
{   
    CONTACTID.Text = customerInfo.ContactID.ToString(); 
    // etc 
} 
0

?再次檢查您的模型並確保兩個表格之間的關係設置正確。這種關係可能從模型中缺失,並導致這個問題。