无法将类型 'System.Collections.Generic.List<website.Class1>' 转换为 'System.Collections.Generic.List<library.Class1>'

Cannot convert type 'System.Collections.Generic.List<website.Class1>' to 'System.Collections.Generic.List<library.Class1>'

我在 .net 4.5 上使用 MVC。

我已将模型从网站分离到 class 库中,并将 .edmx 的 tt class 文件复制到我的网站,以便我可以访问模型 classes。

尽管当我 return 像这样从库中获取一些数据时,

List<website.Class1> a = objLibraryRef.GetFileLists1();

我收到这个错误。

Cannot convert type 'System.Collections.Generic.List<website.Class1>'
to 'System.Collections.Generic.List<library.Class1>'

我不想引用 class 库来访问模型 classes。

如有任何帮助,我们将不胜感激。 谢谢和干杯。

您必须将 library.Class1 转换为 website.Class1。即使它们具有相同的名称,类 也是不同的,因为它们位于不同的库中。

List<website.Class1> a = objLibraryRef.GetFileLists1()
                         .Select(c => new website.Class1 {
                                   property1 = c.property1,
                                   ...
                                   propertyN = c.propertyN
                          }).ToList();

注意:property1..N 替换为您的属性(即 Name)。为此,您不必引用创建library.Class1的库。

您的 DAL 方法返回 List<T> 类型 Class1,它在 library 命名空间中,而您将它分配给类型 Class1 但它的命名空间不同website1 不是 library.

您可以使用隐式类型变量来推断 DAL 库方法返回的类型:

var list = objLibraryRef.GetFileLists1();

或者,如果您真的想要 website.Class1 类型的列表,那么您必须按照@adricadar 在他的 post.

中建议的那样再次投影到列表上

您可以使用 AutoMapper to map those two objects. Even if your definition matches they are two different classes and you can not just directly convert those. Here 是如何映射列表的示例。