public void PreventDuplicatesWhenUnique() { var name = "John Doe"; var item = new UniqueEntity() { Name = name }; _db.UniqueEntities.Add(item); Assert.Equal(1, _db.SaveChanges()); item = new UniqueEntity() { Name = name }; var context = new ValidationContext(item, _sp, null) { MemberName = "Name" }; var attrib = item.GetType().GetProperty("Name")?.GetCustomAttribute <IndexAttribute>() ?? throw new InvalidOperationException("Missing attribute."); Assert.True(attrib.Unique); var result = attrib.GetValidationResult(item.Name, context); Assert.NotNull(result); Assert.NotEqual(ValidationResult.Success, result); Assert.Matches(@"already\sbeen\sused", result.ErrorMessage); Assert.Contains("Name", result.MemberNames); _db.UniqueEntities.Add(item); var x = Assert.Throws <DbUpdateException>( () => { _db.SaveChanges(); } ); Assert.NotNull(x.InnerException); Assert.Matches("unique", x.InnerException.Message.ToLower()); }
public void PreventDuplicatesWhenUnique() { var a = 1234; var b = 5678; var item = new UniqueEntity() { Name = "FirstItem", ValueA = a, ValueB = b }; _db.UniqueEntities.Add(item); Assert.Equal(1, _db.SaveChanges()); item = new UniqueEntity() { Name = "SecondItem", ValueA = a, ValueB = b }; var context = new ValidationContext(item, _sp, null); var attrib = item.GetType().GetCustomAttribute <CompositeIndexAttribute>() ?? throw new InvalidOperationException("Missing attribute."); Assert.True(attrib.Unique); var result = attrib.GetValidationResult(item, context); Assert.NotNull(result); Assert.NotEqual(ValidationResult.Success, result); Assert.Matches(@"already\sbeen\sused", result.ErrorMessage); Assert.Contains("ValueA", result.MemberNames); Assert.Contains("ValueB", result.MemberNames); _db.UniqueEntities.Add(item); var x = Assert.Throws <DbUpdateException>( () => { _db.SaveChanges(); } ); Assert.NotNull(x.InnerException); Assert.Matches("unique", x.InnerException.Message.ToLower()); }