2013-11-27 153 views
0

我用我的示例中使用了實體框架。我想過濾子實體,但它在運行時會打破程序錯誤:「實體或複雜類型'CodeFirstNamespace.Customer'不能在LINQ to Entities查詢中構造。」誰能幫我?謝謝。實體框架 - 篩選子實體

public class Customer 
    { 
     public int CustomerID { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string Email { get; set; } 
     //public virtual ICollection<Address> Addresses 
     public List<User> Users { get; set; } 
     public List<Address> Addresses { get; set; } 
     public List<Order> Orders { get; set; } 
     public List<CheckProduct> CheckProducts { get; set; } 
    } 

public Customer GetCustomerCheckProduct(string email, Byte checkType) 
    { 
     IQueryable<Customer> customers = context.Set<Customer>().Include("CheckProducts").Where(c => c.Email == email); 
     if (checkType != 0) 
     { 
      var cus = customers.Select(customer => new Customer { CheckProducts = customer.CheckProducts.Where(s => s.CheckType == checkType).ToList() }).SingleOrDefault(); 
      return cus; 
     } 

     return null; 
    } 
+0

爲什麼試圖建立一個基於現有客戶的新客戶? '選擇(客戶=>新客戶...'?您最好的情況是與一位_empty_客戶聯繫,只有Checkproduct。如果您無法構建一個沒有任何其他參數的客戶,這總是會失敗。 – oerkelens

+0

你可以向我展示更詳細的答案嗎?我是一個新手。:( – PhuongTT

+0

你想要多少細節?如果你改變以'var cus ='開頭的行到我答案的行,會發生什麼?:) – oerkelens

回答

1

假設你想要找的第一個(如果有的話)的客戶具有給定類型的CheckProducts,爲什麼不乾脆用這個?

var cus = customers.FirstOrDefault(c => c.CheckProducts.Any(cp => cp.Checktype == checkType)); 
+0

它的工作。是的。你這麼多,我已經讀了一本書,並做了舉個例子。非常感謝。 – PhuongTT

0

要篩選集合導航屬性,你可以做到以下幾點:

var customer = <get customer entity>; 

var filteredCheckProducts = context.Entry(customer) 
    .Collection(c => c.CheckProducts) 
    .Query() 
    .Where(cp => cp.CheckType == checkType) 
    .ToArray(); 
+0

它拋出錯誤在行.Collection:「不能轉換lambda表達式,因爲它不是一個委託類型」字符串「。請幫助我。 – PhuongTT

+0

使用」CheckProducts「,而不是c => c.CheckProducts – Moho