2017-05-01 105 views
0

我有這個模型在C#:我如何解決不能隱式轉換類型System.Collections.Generic.List?

public class interfaceModel 
{ 
    public string interfacename { get; set; } 
    public long id { get; set; } 
} 

和編寫代碼:

public static List<interfaceModel> CompanyInterfaceFetch() 
{ 
    var database = new DataBaseDataContext(); 
    var companyinterface = new CompanyInterface(); 

    var interfacelist = 
       database.CompanyInterfaces.Select(x => new interfaceModel { interfacename = x.InterfaceName, id=x.id}); 
    return interfacelist.ToList(); 
} 

// database model 
public class interfaceModel 
{ 
    public string interfacename { get; set; } 
    public long id { get; set; } 
} 

現在我寫的代碼調用該方法:

public static List<interfaceModel> interfacefetch() 
{ 
    return Database.CompanyInterfaceFetch(); 
} 

,但在這條線:

return Database.CompanyInterfaceFetch(); 

我得到這個錯誤:

Error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List

我該如何解決這個問題?謝謝。

+0

你有兩個'interfaceModel'嗎? –

+0

@ DanielA.White沒有隻有一個interfaceModel –

+1

編譯器說你有2 –

回答

3

您有兩個具有相同名稱的獨立類。看的命名,這是兩者的位置:

  • 控制器>數據庫> interfaceModel
  • 模型> interfaceModel

兩種類型,雖然它們具有相同的名稱,甚至可能有確切相同的領域,不可交換。刪除它們中的任何一個並再次編譯以檢查錯誤以查看您必須做出的調整。

+0

請耐心等待檢查 –

+0

謝謝我的朋友,解決我的問題 –

0

你的錯誤是明顯的:

Error CS0029 Cannot implicitly convert

type 'System.Collections.Generic.List<Web.Controllers.Database.interfaceModel>'

to 'System.Collections.Generic.List<Web.Models.interfaceModel>'

你有在這兩個位置的兩個類型相同的名稱。

如果他們有相同的字段,那麼你應該刪除其中的一個。如果它們不同,那麼您需要在代碼中修復導入,以便CompanyInterfaceFetch()interfacefetch()引用相同的類型。如有必要,請刪除導入並指定完全限定的類名稱(如在例外消息中)。

-1

既然你有兩種類型分佈在不同的命名空間中,你不能從一種類型轉換到另一種類型。

對我而言,從設計的角度來看,它看起來很好!

解決這個問題的方法之一是聘請Automapper

相關問題