使用InjectFrom时如何保持源的值

时间:2012-02-14 13:28:03

标签: asp.net-mvc-3 valueinjecter

通过将值注入我的域对象,我会保留一些属性的值。

实施例

域名模型

public class Person
{
    public string Name { get; set; }
    public Guid ID { get; set; }
    public DateTime CreateAt { get; set; }
    public string Notes { get; set; }
    public IList<string> Tags { get; set; }
}

查看模型

public class PersonViewMode
{
    public string Name { get; set; }
    public Guid ID { get; set; }
    public DateTime CreateAt { get; set; }
    public string Notes { get; set; }
    public IList<string> Tags { get; set; }

    public PersonViewMode() { ID = Guid.NewGuid(); } //You should use this value when it is the Target
}

示例

var p = new Person
            {
                ID = Guid.NewGuid() //Should be ignored!
                ,
                Name = "Riderman"
                ,
                CreateAt = DateTime.Now
                ,
                Notes = "teste de nota"
                ,
                Tags = new[] {"Tag1", "Tag2", "Tag3"}
            };

var pvm = new PersonViewMode();

pvm.InjectFrom(p); //Should use the ID value generated in the class constructor PersonViewMode

1 个答案:

答案 0 :(得分:1)

如果从ViewModel的ID中删除set;,则不会设置;

否则你可以将ID的值保存在一个单独的变量中,并在注入后将其重新放回,

或者您可以创建一个忽略“ID”的自定义值注入,或者接收要忽略的属性列表作为参数


这是自定义注入的示例,它接收要忽略的属性名称列表:

public class MyInj : ConventionInjection
{
    private readonly string[] ignores = new string[] { };

    public MyInj(params string[] ignores)
    {
        this.ignores = ignores;
    }

    protected override bool Match(ConventionInfo c)
    {
        if (ignores.Contains(c.SourceProp.Name)) return false;
        return c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Type == c.TargetProp.Type;
    }
}

并像这样使用它:

pvm.InjectFrom(new MyInj("ID"), p);

如果你需要忽略更多,你可以这样做:

pvm.InjectFrom(new MyInj("ID","Prop2","Prop3"), p);