1

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

例子:

领域模型

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
4

1 回答 1

1

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

否则,您可以将 ID 的值保存在单独的变量中,并在注入后将其放回原处,

或者您可以创建一个自定义 valueinjection 忽略“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); 
于 2012-02-14T16:47:44.163 回答