2014-09-02 128 views
3

我们在Sitecore中使用Glass Mapper,通过我们的模型我们可以获得sitecore字段的值。但是我想通过使用该模型轻松获取sitecore字段(sitecore字段类型),而不用硬编码任何字符串(当使用GetProperty()时,您需要属性名称字符串)到方法中。如何从glassmapper映射的对象属性获取sitecore字段?

所以我写了这个东西来实现这个,但是我不满意2种类型需要在使用时传入,因为当你有一个长的模型标识符时它看起来很糟糕。

public static string SitecoreFieldName<T, TU>(Expression<Func<TU>> expr) 
    { 
     var body = ((MemberExpression)expr.Body); 
     var attribute = (typeof(T).GetProperty(body.Member.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false)[0]) as SitecoreFieldAttribute; 
     return attribute.FieldName; 
    } 

最理想的方法是能够像这样得到它Model.SomeProperty.SitecoreField()。但我无法弄清楚如何从那里做出反应。因为这可能是任何类型的扩展。

谢谢!

+0

我知道我应该检查空数组。所以忽略这个。 – zhankezk 2014-09-02 14:41:30

+2

那么你的问题是什么?看起来很简单,而且对我来说是通用的。 – 2014-09-03 07:27:14

+0

问题是要改进它。在这种情况下,您需要传入两种类型才能使其工作,而在数据绑定上下文中使用它时,它在aspx页上看起来不太好。 – zhankezk 2014-09-03 10:08:32

回答

4
public static string SitecoreFieldName<TModel>(Expression<Func<TModel, object>> field) 
{ 
    var body = field.Body as MemberExpression; 

    if (body == null) 
    { 
     return null; 
    } 

    var attribute = typeof(TModel).GetProperty(body.Member.Name) 
     .GetCustomAttributes(typeof(SitecoreFieldAttribute), true) 
     .FirstOrDefault() as SitecoreFieldAttribute; 

    return attribute != null 
     ? attribute.FieldName 
     : null; 
} 

注意,我把inherit=trueGetCustomAttributes方法调用。
否则继承的属性将被忽略。

+0

对不起,我不能upvote,但谢谢!这正是我所期待的。 – zhankezk 2014-09-03 10:23:51

0

我不明白为什么我的问题得到了投票。所以你认为它已经是完美的代码了?

与其它高级开发人员的帮助下,我今天改进它,所以它不需要2种更多的和更清晰的使用语法:

public static Field GetSitecoreField<T>(T model, Expression<Func<T, object>> expression) where T : ModelBase 
    { 
     var body = ((MemberExpression)expression.Body); 
     var attributes = typeof(T).GetProperty(body.Member.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false); 
     if (attributes.Any()) 
     { 
      var attribute = attributes[0] as SitecoreFieldAttribute; 
      if (attribute != null) 
      { 
       return model.Item.Fields[attribute.FieldName]; 
      } 
     } 
     return null; 
    } 

,我可以只是这样称呼它:

GetSitecoreField(Container.Model<SomeModel>(), x => x.anyField) 

希望它可以帮助任何人使用Sitecore使用Glass Mapper并希望从模型属性获取当前sitecore字段。