2012-10-16 72 views
28

可能重複:
The entity cannot be constructed in a LINQ to Entities query實體或複雜類型'不能在LINQ構建以查詢實體

var tasks = from i in data.Incidents 
        join a in data.Accounts on i.CustomerID equals a.Acct_CID 
        select new Tasks() 
        { 

         creator_id = a.ID, 
         start_date = i.DateOpened, 
         end_date = i.DateCLosed, 
         product_code = i.ProductCode, 
         install_type = i.InstallType, 
         os = i.OSType, 
         details = i.Description, 
         solution = i.Solution, 
         creator_name = i.TechID, 
         category = i.Title, 
         text = "Ticket for" + " " + i.Name, 
         status_id = 7 
        }; 

     foreach (var task in tasks) 
      data.Tasks.Add(task); 
     data.SaveChanges(); 

public class Incidents 
    { 
     [Key] 
     public int IncidentID { get; set; } 
     public string CustomerID { get; set; } 
     public string ProductCode { get; set; } 
     public string TechID { get; set; } 
     public DateTime DateOpened { get; set; } 
     public DateTime DateCLosed { get; set; } 
     public string Title { get; set; } 
     public string Description { get; set; } 
     public string Solution { get; set; } 
     public string Name { get; set; } 
     public string OSType{ get; set; } 
     public string InstallType { get; set; } 
     public string AddOnSoftware { get; set; } 
     public string ScreenShare { get; set; } 
    } 

給我一個錯誤,當我嘗試迭代,我希望對此有所幫助

+4

這不是一個重複的那些問題並沒有從它的外觀您要投射到一個實體而不是常規/匿名類型回答我 – Chazt3n

+0

- 所以IMO他們是一樣的。不要忘記它說*可能*重複。 – James

+0

10-4謝謝。 – Chazt3n

回答

71

在Linq-to-Entities中,您只能投影到匿名類型或常規類。您不能投影到現有的實體類型。你可以使用LINQ到對象,像這樣

var tasks = (from i in data.Incidents 
      join a in data.Accounts on i.CustomerID equals a.Acct_CID 
      select new 
      { 
       creator_id = a.ID, 
       start_date = i.DateOpened, 
       end_date = i.DateCLosed 
       // ... 
      }).AsEnumerable().Select(x => new Tasks { 
       creator_id = x.creator_id, 
       start_date = x.start_date, 
       end_date = x.end_date    
      }).ToList(); 
+0

錯誤無法初始化類型'TRX.CRM.Dashboard.Entities.DashBoard.Tasks'與集合初始值設定項,因爲它沒有實現'系統。 Collections.IEnumerable' – Chazt3n

+0

@ Chazt3n - 我在最後添加了一個ToList。試一試 – Aducci

+0

'ToList'不能解決這個問題。如果它不是匿名類型,則不能使用隱含的字段名稱。 – jwg

相關問題