Dears,
I want to do some weird job which is:
adding attributes dynamically to my model class without adding these attributes directly on each property in the model class.
the whole story is:
I have an MVC project using Code first with domain driven design so i have the following:
Core Class : Employee exists in DDD.Core Project
Model Class : EmployeeModel exists in DDDApp Project [main App]
Now, i wants Model class [EmployeeModel] to have the mapped attributes of core class [Employee].
Note:
To not break down the design, i should not add reference of DDD.Core in DDDApp.
What I have tried:
Actually i made a good progress in that:
In
global.asax File i have loaded all of the DDD.Core classes
string webRootPath = HttpContext.Current.Server.MapPath("~");
string docPath = Path.GetFullPath(Path.Combine(webRootPath, "..\\DDD.Core\\bin\\Debug\\DDD.Core.dll"));
Assembly DDDCore = Assembly.LoadFile(docPath);
Application["DDDCoreAssembly"] = DDDCore;
In
DataAnnotationsModelMetadataProvider class which i inherit, i did the following code:
public class MetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
Assembly DDDCoreAssembly = HttpContext.Current.Application["DDDCoreAssembly"] as Assembly;
if (containerType != null)
{
Type coreModelType = DDDCoreAssembly.GetTypes().Single(x => x.Name == containerType.Name.Replace("Model", ""));
MemberInfo coreClassProperty = coreModelType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (coreClassProperty != null)
{
object[] coreClassPropertyAttributes = coreClassProperty.GetCustomAttributes(true);
foreach (var item in coreClassPropertyAttributes)
{
if (item.GetType() == typeof(RequiredAttribute))
{
RequiredAttribute ra = new RequiredAttribute();
}
else if (item.GetType() == typeof(StringLengthAttribute))
{
StringLengthAttribute sla = new StringLengthAttribute(((System.ComponentModel.DataAnnotations.StringLengthAttribute)(item)).MaximumLength);
sla.MinimumLength = ((System.ComponentModel.DataAnnotations.StringLengthAttribute)(item)).MinimumLength;
sla.ErrorMessage = "el length ya ged3an";
}
else if (item.GetType() == typeof(RegularExpressionAttribute))
{
}
}
}
}
var result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (string.IsNullOrEmpty(result.DisplayName) && containerType != null && propertyName != null)
{
var keyForDisplayValue = string.Format("{0}_{1}", containerType.Name, propertyName);
var translatedValue = MCITemplateV4.Properties.Resources.ResourceManager.GetObject(keyForDisplayValue) as string;
if (!string.IsNullOrEmpty(translatedValue))
{
result.DisplayName = translatedValue;
}
}
return result;
}
}
I just can't add the final step which is adding attributes to the properties dynamically?
So Can any one help me with that?!!!!