automapper可以使用存储库将外键映射到对象吗?

时间:2010-08-19 18:46:00

标签: asp.net-mvc automapper

我正在尝试实体框架代码第一个CTP4。假设我有:

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

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Parent Mother { get; set; }
}

public class TestContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }
}

public class ChildEdit
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int MotherId { get; set; }
}

Mapper.CreateMap<Child, ChildEdit>();

映射到编辑模型不是问题。在我的屏幕上,我通过一些控制(下拉列表,自动填充等)选择母亲,并将母亲的身份证贴在后面:

[HttpPost]
public ActionResult Edit(ChildEdit posted)
{
    var repo = new TestContext();

    var mapped = Mapper.Map<ChildEdit, Child>(posted);  // <------- ???????
}

我该如何解决最后的映射?我不想把Mother_Id放在Child对象中。现在我使用这个解决方案,但我希望它可以在Automapper中解决。

        Mapper.CreateMap<ChildEdit, Child>()
            .ForMember(i => i.Mother, opt => opt.Ignore());

        var mapped = Mapper.Map<ChildEdit, Child>(posted);
        mapped.Mother = repo.Parents.Find(posted.MotherId);

修改 这有效,但现在我必须为每个外键执行此操作(BTW:上下文将在最终解决方案中注入):

        Mapper.CreateMap<ChildEdit, Child>();
            .ForMember(i => i.Mother,
                       opt => opt.MapFrom(o => 
                              new TestContext().Parents.Find(o.MotherId)
                                         )
                      );

我真正喜欢的是:

        Mapper.CreateMap<int, Parent>()
            .ForMember(i => i, 
                       opt => opt.MapFrom(o => new TestContext().Parents.Find(o))
                      );

        Mapper.CreateMap<ChildEdit, Child>();

Automapper有可能吗?

3 个答案:

答案 0 :(得分:18)

首先,我假设您有一个像IRepository<T>

这样的存储库界面

然后创建以下类:

public class EntityConverter<T> : ITypeConverter<int, T>
{
    private readonly IRepository<T> _repository;
    public EntityConverter(IRepository<T> repository)
    {
        _repository = repository;
    }
    public T Convert(ResolutionContext context)
    {
        return _repository.Find(System.Convert.ToInt32(context.SourceValue));       
    }
}

基本上,这个类将用于执行int和domain实体之间的所有转换。它使用实体的“Id”从存储库加载它。 IRepository将使用IoC容器注入到转换器中,但后来会更多。

让我们使用以下命令配置AutoMapper映射:

Mapper.CreateMap<int, Mother>().ConvertUsing<EntityConverter<Mother>>();

我建议创建这个“通用”映射,这样如果你在其他类上有其他对“Mother”的引用,它们就会自动映射而不需要额外的努力。

关于IRepository的依赖注入,如果你使用Castle Windsor,AutoMapper配置也应该有:

IWindsorContainer container = CreateContainer();
Mapper.Initialize(map => map.ConstructServicesUsing(container.Resolve));

我已经使用过这种方法并且效果很好。

答案 1 :(得分:6)

我是这样做的:(使用ValueInjecter
为了展示工作原理,我提出了更大的要求


[TestFixture]
public class JohnLandheer
{
    [Test]
    public void Test()
    {
        var child = new Child
        {
            Id = 1,
            Name = "John",
            Mother = new Parent { Id = 3 },
            Father = new Parent { Id = 9 },
            Brother = new Child { Id = 5 },
            Sister = new Child { Id = 7 }
        };
        var childEdit = new ChildEdit();

        childEdit.InjectFrom(child)
                 .InjectFrom<EntityToInt>(child);

        Assert.AreEqual(1, childEdit.Id);
        Assert.AreEqual("John", childEdit.Name);
        Assert.AreEqual(3, childEdit.MotherId);
        Assert.AreEqual(9, childEdit.FatherId);
        Assert.AreEqual(5, childEdit.BrotherId);
        Assert.AreEqual(7, childEdit.SisterId);
        Assert.AreEqual(0, childEdit.Sister2Id);

        var c = new Child();

        c.InjectFrom(childEdit)
            .InjectFrom<IntToEntity>(childEdit);

        Assert.AreEqual(1, c.Id);
        Assert.AreEqual("John", c.Name);
        Assert.AreEqual(3, c.Mother.Id);
        Assert.AreEqual(9, c.Father.Id);
        Assert.AreEqual(5, c.Brother.Id);
        Assert.AreEqual(7, c.Sister.Id);
        Assert.AreEqual(null, c.Sister2);
    }

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

    public class Parent : Entity
    {
        public string Name { get; set; }
    }

    public class Child : Entity
    {
        public string Name { get; set; }
        public Parent Mother { get; set; }
        public Parent Father { get; set; }
        public Child Brother { get; set; }
        public Child Sister { get; set; }
        public Child Sister2 { get; set; }
    }

    public class ChildEdit
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int MotherId { get; set; }
        public int FatherId { get; set; }
        public int BrotherId { get; set; }
        public int SisterId { get; set; }
        public int Sister2Id { get; set; }
    }

    public class EntityToInt : LoopValueInjection
    {
        protected override bool TypesMatch(Type sourceType, Type targetType)
        {
            return sourceType.IsSubclassOf(typeof(Entity)) && targetType == typeof(int);
        }

        protected override string TargetPropName(string sourcePropName)
        {
            return sourcePropName + "Id";
        }

        protected override bool AllowSetValue(object value)
        {
            return value != null;
        }

        protected override object SetValue(object sourcePropertyValue)
        {
            return (sourcePropertyValue as Entity).Id;
        }
    }

    public class IntToEntity : LoopValueInjection
    {
        protected override bool TypesMatch(Type sourceType, Type targetType)
        {
            return sourceType == typeof(int) && targetType.IsSubclassOf(typeof(Entity));
        }

        protected override string TargetPropName(string sourcePropName)
        {
            return sourcePropName.RemoveSuffix("Id");
        }

        protected override bool AllowSetValue(object value)
        {
            return (int)value > 0;
        }

        protected override object SetValue(object sourcePropertyValue)
        {
            // you could as well do repoType = IoC.Resolve(typeof(IRepo<>).MakeGenericType(TargetPropType))
            var repoType =  typeof (Repo<>).MakeGenericType(TargetPropType);
            var repo = Activator.CreateInstance(repoType);
            return repoType.GetMethod("Get").Invoke(repo, new[] {sourcePropertyValue});
        }
    }

    class Repo<T> : IRepo<T> where T : Entity, new()
    {
        public T Get(int id)
        {
            return new T{Id = id};
        }
    }

    private interface IRepo<T>
    {
        T Get(int id);
    }
}

答案 2 :(得分:3)

也可以用这种方式在EF中定义外键:

[ForeignKey("MotherId")]
public virtual Parent Mother { get; set; }
public int MotherId { get; set; }

在这种情况下,没有必要进行额外的查询来查找母亲。只需将ViewModel的MotherId分配给Model的MotherId。