2

是否有任何框架可以执行以下操作:

var source = new Entity()
{
    StringProp = null,
    IntProp = 100,

};

var target = new Entity()
{
    StringProp = "stringValue", // Property value should remain the same if source value is null 
    IntProp = 222
};

var mergedEntity = MergeFramework.Merge(source, target); // Here is what I am looking for

Assert.AreEqual(100, mergedEntity.IntField);
Assert.AreEqual("stringValue", mergedEntity.StringField);

以下是我需要它的工作流程:

  1. 应用获取实体实例。实例的某些属性为空。(源实例)

  2. 应用程序从数据库中获取与源中具有相同身份的实体。(目标实例)

  3. 合并两个实体并保存合并到数据库。

主要问题是我的项目中有近600个实体,所以我不想手动为每个实体编写合并逻辑。基本上,我正在寻找像 AutoMapper 或 ValueInjecter 这样灵活的东西,它们满足以下要求:

  • 提供指定类型合并条件的可能性。例如:如果 source.IntProp == int.MinInt -> 不合并属性

  • 提供指定属性特定条件的可能性。就像在 AutoMapper 中一样:

    Mapper.CreateMap().ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date));

4

2 回答 2

1

干得好:

using System;
using NUnit.Framework;
using Omu.ValueInjecter;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            var source = new Entity()
            {
                StringProp = null,
                IntProp = 100,

            };

            var target = new Entity()
            {
                StringProp = "stringValue", // Property value should remain the same if source value is null 
                IntProp = 222
            };

            var mergedEntity = (Entity) target.InjectFrom<Merge>(source);

            Assert.AreEqual(100, mergedEntity.IntProp);
            Assert.AreEqual("stringValue", mergedEntity.StringProp);
            Console.WriteLine("ok");
        }
    }

    public class Merge : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            return c.SourceProp.Name == c.TargetProp.Name
                   && c.SourceProp.Value != null;
        }
    }

    public class Entity
    {
        public string StringProp { get; set; }

        public int IntProp { get; set; }
    }

}
于 2012-04-15T10:15:17.613 回答
0

要更新当前答案,ConventionInjection已弃用。您现在可以LoopInjection在创建自定义注入时使用。

Merge更新的Injection 类的示例:

public class Merge : LoopInjection
{

    protected override bool MatchTypes(Type source, Type target)
    {
        return source.Name == target.Name;
    }

    protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
    {
        if (sp.GetValue(source) == null) return;
        base.SetValue(source, target, sp, tp);
    }

}
于 2016-10-26T14:47:51.683 回答