2013-02-26 77 views
0

我试图将业务对象映射到数据优先自动生成的实体。然而,Iam在我的mapper类中得到一个错误,我返回new Lab将映射的业务对象返回到EF实体部分类时出错

的错误是"Cannot Convert expression type 'LabManager.DataAcces.Lab' to return type LabManager.BusinessObjects.BusinessObjects.Lab"

我的问题是:为什么我收到的时候我回正是,预计我的映射类这个错误?

我的业务对象是这样的:

namespace LabManager.BusinessObjects.BusinessObjects 
{ 
    public class Lab 
    { 
     public Lab() 
     { 

     } 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public IList<Cylinder> Cylinders { get; set; } 
    } 
} 

实体我映射的业务对象是:

public partial class Lab 
{ 
    public Lab() 
    { 
     this.Cylinders = new HashSet<Cylinder>(); 
    } 

    public int Id { get; set; } 
    public string Name { get; set; } 

    public virtual ICollection<Cylinder> Cylinders { get; set; } 
} 

,我只是用手工卷制的映射类(无AutoMapper ):

namespace EmitLabManager.DataAccess.ModelMapper 
public class Mapper 
{ 
    internal static BusinessObjects.BusinessObjects.Lab GetLabs(Lab entity) 
    { 
     return new Lab 
     { 
      Id = entity.Id, 
      Name = entity.Name, 
      Cylinders = entity.Cylinders 
     }; 
    } 
} 
+0

为什么你只在方法声明中使用完整类型名称,而不是在任何地方使用? – Kniganapolke 2013-02-26 15:43:04

+0

@Kniganapolke这是一个很好的问题。我想我应该。我以前从来没有真正需要这样的资格。我通常会尽量保持对象名称的独特性,因此不必以此方式进行限定。我很可能会重构名称和冗余名称空间(BusinessObjects.BusinessObjects)。 – 2013-02-26 15:54:56

回答

1

您很可能有名称空间冲突。您需要完全限定您的GetLabs函数中的构造函数:

return new BusinessObjects.BusinessObjects.Lab 
    { 
     Id = entity.Id, 
     Name = entity.Name, 
     Cylinders = entity.Cylinders 
    }; 

这应该有所斩断。

+0

感谢您的回答。将该名称空间添加到初始化程序中,清除了ID和名称上的“红色”,但我在初始化柱面的行上继续出现错误。现在的错误是''不能将源类型System.Collections.Generic.ICollection '转换为目标类型'System.Collections.Generic.ICollection ''这仍然是命名空间问题? – 2013-02-26 15:52:46

+0

参数的完全限定类型 – Kniganapolke 2013-02-26 15:58:35

+0

是的,这是同样的问题。但是,您需要为entity.Cylinders类编写一个转换方法 - 名称与Cylinders属性相同你的Lab对象,但它们实际上是完全不同的对象,EF可能已经为你创建了一个转换器;否则,你将不得不创建一个新的BusinessObjects.Cylinder,并从DataAccess.Cylinder中一个一个地分配属性。 – 2013-02-26 15:58:46