2017-05-01 67 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

相关问题