我们来看看这些课程:
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public string ExtraProp { get; set; }
}
public class Parent
{
public int Id { get; set; }
public string Text { get; set; }
public Child Child { get; set; }
public string ParentExtraProp { get; set; }
}
public class ChildVo
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ParentVo
{
public int Id { get; set; }
public string Text { get; set; }
public ChildVo Child { get; set; }
}
自动映射:
Mapper.CreateMap<Child, ChildVo>();
//.ForSourceMember(x => x.ExtraProp, o => o.Ignore()); //does not help
//.IgnoreAllNonExisting(); //does not help
Mapper.CreateMap<Parent, ParentVo>();
并在Linq中查询到Nhibernate:
var test = Session.Query<Parent>()
.Where(x => x.Id == myId)
.ProjectTo<ParentVo>()
.ToList();
ProjectTo只选择在ParentVo中定义的列(属性)(不是来自Parent类的所有属性) - 这很好。但是从Child类中选择所有列(属性),尽管它们没有在ChildVo中定义。 为什么Automapper会忽略我的嵌套属性映射?是否可以在投影期间使用所有已定义的映射?
答案 0 :(得分:1)
虽然我不熟悉nhibernate,但您在此处执行的相同测试在Entity Framework中运行良好。在EF中,您可以看到在执行之前生成的查询 - 尝试执行此操作并查看是否显示其他列。
public class TestContext : DbContext {
public DbSet<Parent> Parents { get; set; }
}
var query = testContext.Parents.ProjectTo<ParentVo>();
Console.WriteLine(query.ToString());
这会产生以下输出(注意没有ExtraProp):
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Text] AS [Text],
CASE WHEN ([Extent2].[Id] IS NOT NULL) THEN 1 END AS [C1],
[Extent1].[Child_Id] AS [Child_Id],
[Extent2].[Name] AS [Name]
FROM [dbo].[Parents] AS [Extent1]
LEFT OUTER JOIN [dbo].[Children] AS [Extent2] ON [Extent1].[Child_Id] = [Extent2].[Id]
这让我觉得问题不是AutoMapper,而是看不到生成的查询,这很难说。