forked from tpolyak/Sharp-Architecture
-
Notifications
You must be signed in to change notification settings - Fork 153
/
EntityCollectionValueBinder.cs
63 lines (50 loc) · 2.33 KB
/
EntityCollectionValueBinder.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
57
58
59
60
61
62
63
namespace SharpArch.Web.ModelBinder
{
using System;
using System.Linq;
using System.Web.Mvc;
using SharpArch.Core.DomainModel;
internal class EntityCollectionValueBinder : DefaultModelBinder
{
/// <summary>
/// Binds the model to a value by using the specified controller context and binding context.
/// </summary>
/// <returns>
/// The bound value.
/// </returns>
/// <param name = "controllerContext">The controller context.</param>
/// <param name = "bindingContext">The binding context.</param>
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var collectionType = bindingContext.ModelType;
var collectionEntityType = collectionType.GetGenericArguments().First();
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult != null)
{
var rawValue = valueProviderResult.RawValue as string[];
var countOfEntityIds = rawValue.Length;
var entities = Array.CreateInstance(collectionEntityType, countOfEntityIds);
var entityInterfaceType =
collectionEntityType.GetInterfaces().First(
interfaceType =>
interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
var idType = entityInterfaceType.GetGenericArguments().First();
for (var i = 0; i < countOfEntityIds; i++)
{
var rawId = rawValue[i];
if (string.IsNullOrEmpty(rawId))
{
return null;
}
var typedId = (idType == typeof(Guid)) ? new Guid(rawId) : Convert.ChangeType(rawId, idType);
var entity = ValueBinderHelper.GetEntityFor(collectionEntityType, typedId, idType);
entities.SetValue(entity, i);
}
// base.BindModel(controllerContext, bindingContext);
return entities;
}
return base.BindModel(controllerContext, bindingContext);
}
}
}