-
Notifications
You must be signed in to change notification settings - Fork 27
/
ContentPartDefinitionBuilderExtensions.cs
56 lines (48 loc) · 2.24 KB
/
ContentPartDefinitionBuilderExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using OrchardCore.ContentManagement.Metadata.Settings;
using System;
using System.Linq.Expressions;
namespace OrchardCore.ContentManagement.Metadata.Builders;
public static class ContentPartDefinitionBuilderExtensions
{
/// <summary>
/// Wraps an existing <see cref="ContentPartDefinitionBuilder"/> into a wrapped type.
/// </summary>
public static ContentPartDefinitionBuilder<TPart> AsPart<TPart>(this ContentPartDefinitionBuilder builder)
where TPart : ContentPart =>
new(builder);
}
public class ContentPartDefinitionBuilder<TPart>
where TPart : ContentPart
{
public ContentPartDefinitionBuilder Builder { get; private set; }
public ContentPartDefinitionBuilder(ContentPartDefinitionBuilder builder) => Builder = builder;
public ContentPartDefinitionBuilder<TPart> Configure(Action<ContentPartDefinitionBuilder> configureAction)
{
configureAction(Builder);
return this;
}
/// <summary>
/// Creates a field by getting the technical name and field type using a lambda expression rather than relying on
/// developer provided strings. This improves the coupling between the part and the field. Also sets the display
/// name to the field's technical name by default, but if a more natural name is needed it can be overwritten in the
/// <paramref name="configuration"/>.
/// </summary>
/// <param name="fieldPropertySelector">The expression which gets the part and returns its field.</param>
/// <param name="configuration">Any further configuration, can override the automatic settings.</param>
/// <typeparam name="TField">The type of the new field to be attached to the content part.</typeparam>
public ContentPartDefinitionBuilder<TPart> WithField<TField>(
Expression<Func<TPart, TField>> fieldPropertySelector,
Action<ContentPartFieldDefinitionBuilder> configuration = null)
{
var property = ((MemberExpression)fieldPropertySelector.Body).Member;
var name = property.Name;
Builder = Builder.WithField(
name,
field =>
{
field = field.WithDisplayName(name).OfType(typeof(TField).Name);
configuration?.Invoke(field);
});
return this;
}
}