繁体   English   中英

使用 AutoMapper 和实体框架映射具有复杂类型的实体时出现 NotSuportedException

[英]NotSuportedException when mapping entities with complex types using AutoMapper and Entity Framework

我想将具有复杂类型的实体映射到另一个实体。 但是,在Main方法的最后一行中

System.NotSupportedException:无法比较“ConsoleApplication2.ComplexType”类型的元素。 仅支持原始类型、枚举类型和实体类型。

引发异常。

如何解决?

我知道我可以将复杂类型的属性展平到实体。 但是,它涉及大量代码重复,因此我强烈喜欢一种不需要我将复杂类型属性展平到实体的解决方案。 复杂类型本身包含其他复杂类型,因此解决方案应该允许将复杂类型嵌套到复杂类型。

实体框架 6.1.3、AutoMapper 3.3.1 和 4.0.4、SQL Server 2014 SP1 Express、VS 2015、.NET 4.5.2 和 4.6。

如果.SingleOrDefault(x => x.Id == 1).ProjectTo<MappedEntity>()被删除,它会起作用。

如果.SingleOrDefault(x => x.Id == 1)被重写为.Where(x => x.Id == 1).ToList().SingleOrDefault();如果仍然不起作用 .

GitHub 问题: https : //github.com/AutoMapper/AutoMapper/issues/925

using System.Data.Entity;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseAlways<ClientContext>());

            Mapper.CreateMap<Entity, MappedEntity>();
            Mapper.CreateMap<ComplexType, MappedComplexType>();

            var clientContext = new ClientContext();
            clientContext.Set<Entity>().ProjectTo<MappedEntity>().SingleOrDefault(x => x.Id == 1);
        }
    }

    class ClientContext : DbContext
    {
        public virtual DbSet<Entity> Entities { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Entity>().HasKey(x => x.Id);
            modelBuilder.ComplexType<ComplexType>();
        }
    }

    class Entity
    {
        public virtual int Id { get; set; }

        public virtual ComplexType ComplexType { get; set; }
    }

    class ComplexType
    {
        public virtual string Field { get; set; }
    }

    class MappedEntity
    {
        public virtual int Id { get; set; }

        public virtual MappedComplexType ComplexType { get; set; }
    }

    class MappedComplexType
    {
        public virtual string Field { get; set; }
    }
}

这可以帮助:

....Configuration.AllowNullDestinationValues = false;

但这会导致其他地图出现问题! 所以我们可以从配置中为我们的 ComplexType 设置它:

....cfg.ForAllPropertyMaps(p => p.SourceType == typeof(ComplexType), (p, q) => { q.AllowNull(); });
  • 相关有用的链接:

https://www.csharpcodi.com/csharp-examples/AutoMapper.IProfileExpression.ForAllPropertyMaps(System.Func,%20System.Action)/

https://docs.automapper.org/en/stable/10.0-Upgrade-Guide.html?highlight=AllowNullDestinationValues#allownull-allows-you-to-override-per-member-allownulldestinationvalues-and-allownullcollections

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM