DataAnnotations “NotRequired” attribute

后端 未结 4 1339
天涯浪人
天涯浪人 2021-02-13 19:13

I\'ve a model kind of complicated.

I have my UserViewModel which has several properties and two of them are HomePhone and WorkPhone

4条回答
  •  既然无缘
    2021-02-13 19:37

    I've been using this amazing nuget that does dynamic annotations: ExpressiveAnnotations

    It allows you to do things that weren't possible before such as

    [AssertThat("ReturnDate >= Today()")]
    public DateTime? ReturnDate { get; set; }
    

    or even

    public bool GoAbroad { get; set; }
    [RequiredIf("GoAbroad == true")]
    public string PassportNumber { get; set; }
    

    Update: Compile annotations in a unit test to ensure no errors exist

    As mentioned by @diego this might be intimidating to write code in a string, but the following is what I use to Unit Test all validations looking for compilation errors.

    namespace UnitTest
    {
        public static class ExpressiveAnnotationTestHelpers
        {
            public static IEnumerable CompileExpressiveAttributes(this Type type)
            {
                var properties = type.GetProperties()
                    .Where(p => Attribute.IsDefined(p, typeof(ExpressiveAttribute)));
                var attributes = new List();
                foreach (var prop in properties)
                {
                    var attribs = prop.GetCustomAttributes().ToList();
                    attribs.ForEach(x => x.Compile(prop.DeclaringType));
                    attributes.AddRange(attribs);
                }
                return attributes;
            }
        }
        [TestClass]
        public class ExpressiveAnnotationTests
        {
            [TestMethod]
            public void CompileAnnotationsTest()
            {
                // ... or for all assemblies within current domain:
                var compiled = Assembly.Load("NamespaceOfEntitiesWithExpressiveAnnotations").GetTypes()
                    .SelectMany(t => t.CompileExpressiveAttributes()).ToList();
    
                Console.WriteLine($"Total entities using Expressive Annotations: {compiled.Count}");
    
                foreach (var compileItem in compiled)
                {
                    Console.WriteLine($"Expression: {compileItem.Expression}");
                }
    
                Assert.IsTrue(compiled.Count > 0);
            }
    
    
        }
    }
    

提交回复
热议问题