public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e) { base.ElementPropertyChanged(e); ModelAttribute element = (ModelAttribute)e.ModelElement; if (element.IsDeleted) { return; } ModelClass modelClass = element.ModelClass; ModelRoot modelRoot = element.Store.ModelRoot(); Store store = element.Store; Transaction current = store.TransactionManager.CurrentTransaction; if (current.IsSerializing || ModelRoot.BatchUpdating) { return; } if (Equals(e.NewValue, e.OldValue)) { return; } List <string> errorMessages = EFCoreValidator.GetErrors(element).ToList(); switch (e.DomainProperty.Name) { case "AutoProperty": { if (element.AutoProperty) { element.PersistencePoint = PersistencePointType.Property; element.ImplementNotify = false; } } break; case "IdentityType": { if (element.IsIdentity) { if (element.IdentityType == IdentityType.None) { errorMessages.Add($"{modelClass.Name}.{element.Name}: Identity properties must have an identity type defined"); } } else { element.IdentityType = IdentityType.None; } } break; case "ImplementNotify": { if (element.IsIdentity) { element.ImplementNotify = false; } if (element.ImplementNotify) { element.AutoProperty = false; } } break; case "Indexed": { if (element.IsIdentity) { element.Indexed = true; } if (element.IsConcurrencyToken) { element.Indexed = false; } if (element.Indexed) { element.Persistent = true; } } break; case "InitialValue": { string newInitialValue = (string)e.NewValue; // if the property is an Enum and the user just typed the name of the Enum value without the Enum type name, help them out if (element.ModelClass.ModelRoot.Enums.Any(x => x.Name == element.Type) && !newInitialValue.Contains(".")) { newInitialValue = element.InitialValue = $"{element.Type}.{newInitialValue}"; } if (!element.IsValidInitialValue(null, newInitialValue)) { errorMessages.Add($"{modelClass.Name}.{element.Name}: {newInitialValue} isn't a valid value for {element.Type}"); } } break; case "IsConcurrencyToken": { bool newIsConcurrencyToken = (bool)e.NewValue; if (newIsConcurrencyToken) { element.IsIdentity = false; element.Persistent = true; element.Required = true; element.Type = "Binary"; } } break; case "IsIdentity": { bool newIsIdentity = (bool)e.NewValue; if (newIsIdentity) { if (element.ModelClass.IsDependentType) { errorMessages.Add($"{modelClass.Name}.{element.Name}: Can't make {element.Name} an identity because {modelClass.Name} is a dependent type and can't have an identity property."); } else { if (!modelRoot.ValidIdentityAttributeTypes.Contains(element.Type)) { errorMessages.Add($"{modelClass.Name}.{element.Name}: Properties of type {element.Type} can't be used as identity properties."); } else { element.IsConcurrencyToken = false; element.Indexed = true; element.IndexedUnique = true; element.Persistent = true; element.Required = true; if (element.IdentityType == IdentityType.None) { element.IdentityType = IdentityType.AutoGenerated; } } } } else { element.IdentityType = IdentityType.None; } } break; case "MinLength": { int minLengthValue = (int)e.NewValue; if (element.Type != "String") { element.MinLength = 0; } else if (minLengthValue < 0) { errorMessages.Add($"{modelClass.Name}.{element.Name}: MinLength must be zero or a positive number"); } else if (element.MaxLength > 0 && minLengthValue > element.MaxLength) { errorMessages.Add($"{modelClass.Name}.{element.Name}: MinLength cannot be greater than MaxLength"); } } break; case "MaxLength": { if (element.Type != "String") { element.MaxLength = null; } else { int?maxLengthValue = (int?)e.NewValue; if (maxLengthValue > 0 && element.MinLength > maxLengthValue) { errorMessages.Add($"{modelClass.Name}.{element.Name}: MinLength cannot be greater than MaxLength"); } } } break; case "Name": { string newName = (string)e.NewValue; if (string.IsNullOrEmpty(newName)) { errorMessages.Add("Name must be a valid .NET identifier"); } else { ParseResult fragment; try { fragment = ModelAttribute.Parse(modelRoot, newName); if (fragment == null) { errorMessages.Add($"{modelClass.Name}: Could not parse entry '{newName}'"); } else { if (string.IsNullOrEmpty(fragment.Name) || !CodeGenerator.IsValidLanguageIndependentIdentifier(fragment.Name)) { errorMessages.Add($"{modelClass.Name}: Property name '{fragment.Name}' isn't a valid .NET identifier"); } else if (modelClass.AllAttributes.Except(new[] { element }).Any(x => x.Name == fragment.Name)) { errorMessages.Add($"{modelClass.Name}: Property name '{fragment.Name}' already in use"); } else if (modelClass.AllNavigationProperties().Any(p => p.PropertyName == fragment.Name)) { errorMessages.Add($"{modelClass.Name}: Property name '{fragment.Name}' already in use"); } else { element.Name = fragment.Name; if (fragment.Type != null) { element.Type = fragment.Type; } if (fragment.Required != null) { element.Required = fragment.Required.Value; } element.MaxLength = fragment.MaxLength; element.MinLength = fragment.MinLength ?? 0; if (fragment.InitialValue != null) { element.InitialValue = fragment.InitialValue; } if (fragment.IsIdentity) { element.IsIdentity = true; // don't reset to false if not entered as part of name } } } } catch (Exception exception) { errorMessages.Add($"{modelClass.Name}: Could not parse entry '{newName}': {exception.Message}"); } } } break; case "PersistencePoint": { if ((PersistencePointType)e.NewValue == PersistencePointType.Field) { element.AutoProperty = false; } } break; case "Persistent": { bool newPersistent = (bool)e.NewValue; if (!newPersistent) { element.IsIdentity = false; element.Indexed = false; element.IndexedUnique = false; element.IdentityType = IdentityType.None; element.IsConcurrencyToken = false; element.Virtual = false; } } break; case "ReadOnly": { if (!element.Persistent || element.SetterVisibility != SetterAccessModifier.Public) { element.ReadOnly = false; } } break; case "Required": { bool newRequired = (bool)e.NewValue; if (!newRequired) { if (element.IsIdentity || element.IsConcurrencyToken) { element.Required = true; } } } break; case "Type": { string newType = (string)e.NewValue; if (element.IsIdentity) { if (!modelRoot.ValidIdentityAttributeTypes.Contains(ModelAttribute.ToCLRType(newType))) { errorMessages.Add($"{modelClass.Name}.{element.Name}: Properties of type {newType} can't be used as identity properties."); } else { element.Required = true; element.Persistent = true; } } if (newType != "String") { element.MaxLength = null; element.MinLength = 0; element.StringType = HTML5Type.None; } else { if (!element.IsValidInitialValue(newType)) { element.InitialValue = null; } } if (element.IsConcurrencyToken) { element.Type = "Binary"; } if (!element.SupportsInitialValue) { element.InitialValue = null; } } break; } errorMessages = errorMessages.Where(m => m != null).ToList(); if (errorMessages.Any()) { current.Rollback(); ErrorDisplay.Show(string.Join("\n", errorMessages)); } }
private void ProcessProperties([NotNull] ClassDeclarationSyntax classDecl) { if (classDecl == null) { throw new ArgumentNullException(nameof(classDecl)); } Transaction tx = Store.TransactionManager.CurrentTransaction == null ? Store.TransactionManager.BeginTransaction() : null; try { string className = classDecl.Identifier.Text; ModelRoot modelRoot = Store.ModelRoot(); ModelClass modelClass = Store.Get <ModelClass>().FirstOrDefault(c => c.Name == className); modelClass.Attributes.Clear(); foreach (PropertyDeclarationSyntax propertyDecl in classDecl.DescendantNodes().OfType <PropertyDeclarationSyntax>()) { // if the property has a fat arrow expression as its direct descendent, it's a readonly calculated property // TODO: we should handle this // but for this release, ignore it if (propertyDecl.ChildNodes().OfType <ArrowExpressionClauseSyntax>().Any()) { continue; } AccessorDeclarationSyntax getAccessor = (AccessorDeclarationSyntax)propertyDecl.DescendantNodes().FirstOrDefault(node => node.IsKind(SyntaxKind.GetAccessorDeclaration)); AccessorDeclarationSyntax setAccessor = (AccessorDeclarationSyntax)propertyDecl.DescendantNodes().FirstOrDefault(node => node.IsKind(SyntaxKind.SetAccessorDeclaration)); // if there's no getAccessor, why are we bothering? if (getAccessor == null) { continue; } string propertyName = propertyDecl.Identifier.ToString(); string propertyType = propertyDecl.Type.ToString(); ModelClass target = modelRoot.Classes.FirstOrDefault(t => t.Name == propertyType); // is the property type a generic? // assume it's a list // TODO: this really isn't a good assumption. Fix later if (propertyDecl.ChildNodes().OfType <GenericNameSyntax>().Any()) { GenericNameSyntax genericDecl = propertyDecl.ChildNodes().OfType <GenericNameSyntax>().FirstOrDefault(); List <string> contentTypes = genericDecl.DescendantNodes().OfType <IdentifierNameSyntax>().Select(i => i.Identifier.ToString()).ToList(); // there can only be one generic argument if (contentTypes.Count != 1) { WarningDisplay.Show($"Found {className}.{propertyName}, but its type ({genericDecl.Identifier}<{String.Join(", ", contentTypes)}>) isn't anything expected. Ignoring..."); continue; } propertyType = contentTypes[0]; target = modelRoot.Classes.FirstOrDefault(t => t.Name == propertyType); if (target == null) { target = new ModelClass(Store, new PropertyAssignment(ModelClass.NameDomainPropertyId, propertyType)); modelRoot.Classes.Add(target); } ProcessAssociation(modelClass, target, propertyDecl, true); continue; } // is the property type an existing ModelClass? if (target != null) { ProcessAssociation(modelClass, target, propertyDecl); continue; } bool propertyShowsNullable = propertyDecl.DescendantNodes().OfType <NullableTypeSyntax>().Any(); // is the property type something we don't know about? if (!modelRoot.IsValidCLRType(propertyType)) { // might be an enum. If so, we'll handle it like a CLR type // if it's nullable, it's definitely an enum, but if we don't know about it, it could be an enum or a class if (!KnownEnums.Contains(propertyType) && !propertyShowsNullable) { // assume it's a class and create the class target = new ModelClass(Store, new PropertyAssignment(ModelClass.NameDomainPropertyId, propertyType)); modelRoot.Classes.Add(target); ProcessAssociation(modelClass, target, propertyDecl); continue; } } // if we're here, it's just a property (CLR or enum) try { // ReSharper disable once UseObjectOrCollectionInitializer ModelAttribute modelAttribute = new ModelAttribute(Store, new PropertyAssignment(ModelAttribute.NameDomainPropertyId, propertyName)) { Type = ModelAttribute.ToCLRType(propertyDecl.Type.ToString()).Trim('?'), Required = propertyDecl.HasAttribute("RequiredAttribute") || !propertyShowsNullable, Indexed = propertyDecl.HasAttribute("IndexedAttribute"), IsIdentity = propertyDecl.HasAttribute("KeyAttribute"), Virtual = propertyDecl.DescendantTokens().Any(t => t.IsKind(SyntaxKind.VirtualKeyword)) }; if (modelAttribute.Type.ToLower() == "string") { AttributeSyntax maxLengthAttribute = propertyDecl.GetAttribute("MaxLengthAttribute"); AttributeArgumentSyntax maxLength = maxLengthAttribute?.GetAttributeArguments()?.FirstOrDefault(); if (maxLength != null) { modelAttribute.MaxLength = TryParse(maxLength.Expression.ToString(), out int _max) ? _max : -1; } AttributeSyntax minLengthAttribute = propertyDecl.GetAttribute("MinLengthAttribute"); AttributeArgumentSyntax minLength = minLengthAttribute?.GetAttributeArguments()?.FirstOrDefault(); if (minLength != null) { modelAttribute.MinLength = TryParse(minLength.Expression.ToString(), out int _min) ? _min : 0; } } else { modelAttribute.MaxLength = -1; modelAttribute.MinLength = 0; } // if no setAccessor, it's a calculated readonly property if (setAccessor == null) { modelAttribute.Persistent = false; modelAttribute.ReadOnly = true; } modelAttribute.AutoProperty = !getAccessor.DescendantNodes().Any(node => node.IsKind(SyntaxKind.Block)) && !setAccessor.DescendantNodes().Any(node => node.IsKind(SyntaxKind.Block)); modelAttribute.SetterVisibility = setAccessor.Modifiers.Any(m => m.ToString() == "protected") ? SetterAccessModifier.Protected : setAccessor.Modifiers.Any(m => m.ToString() == "internal") ? SetterAccessModifier.Internal : SetterAccessModifier.Public; XMLDocumentation xmlDocumentation = new XMLDocumentation(propertyDecl); modelAttribute.Summary = xmlDocumentation.Summary; modelAttribute.Description = xmlDocumentation.Description; modelClass.Attributes.Add(modelAttribute); } catch { WarningDisplay.Show($"Could not parse '{className}.{propertyDecl.Identifier}'."); } } } catch { tx = null; throw; } finally { tx?.Commit(); } }
/// <inheritdoc /> public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e) { base.ElementPropertyChanged(e); ModelAttribute element = (ModelAttribute)e.ModelElement; if (element.IsDeleted) { return; } ModelClass modelClass = element.ModelClass; ModelRoot modelRoot = element.Store.ModelRoot(); Store store = element.Store; Transaction current = store.TransactionManager.CurrentTransaction; if (current.IsSerializing || ModelRoot.BatchUpdating) { return; } if (Equals(e.NewValue, e.OldValue)) { return; } List <string> errorMessages = new List <string>(); switch (e.DomainProperty.Name) { case "AutoProperty": { if (element.AutoProperty) { //element.PersistencePoint = PersistencePointType.Property; element.ImplementNotify = false; } else { if (string.IsNullOrEmpty(element.BackingFieldName)) { element.BackingFieldName = $"_{element.Name.ToCamelCase()}"; } } } break; case "IdentityType": { if (element.IsIdentity) { if (element.IdentityType == IdentityType.None) { errorMessages.Add($"{modelClass.Name}.{element.Name}: Identity properties must have an identity type defined"); } foreach (Association association in element.ModelClass.LocalNavigationProperties() .Where(nav => nav.AssociationObject.Dependent == element.ModelClass) .Select(nav => nav.AssociationObject) .Where(a => !string.IsNullOrWhiteSpace(a.FKPropertyName) && a.FKPropertyName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Any(n => n.Trim() == element.Name))) { foreach (ModelAttribute attribute in association.GetFKAutoIdentityErrors()) { errorMessages.Add($"{association.Source.Name} <=> {association.Target.Name}: FK property {attribute.Name} in {association.Dependent.FullName} is an auto-generated identity. Migration will fail."); } } } else { element.IdentityType = IdentityType.None; } } break; case "ImplementNotify": { if (element.IsIdentity) { element.ImplementNotify = false; } if (element.ImplementNotify) { element.AutoProperty = false; } } break; case "Indexed": { if (element.IsIdentity) { element.Indexed = true; } if (element.IsConcurrencyToken) { element.Indexed = false; } if (element.Indexed) { element.Persistent = true; } } break; case "InitialValue": { string newInitialValue = (string)e.NewValue; if (string.IsNullOrEmpty(newInitialValue)) { break; } // if the property is an Enum and the user just typed the name of the Enum value without the Enum type name, help them out if (element.ModelClass.ModelRoot.Enums.Any(x => x.Name == element.Type) && !newInitialValue.Contains(".")) { newInitialValue = element.InitialValue = $"{element.Type}.{newInitialValue}"; } if (!element.IsValidInitialValue(null, newInitialValue)) { errorMessages.Add($"{modelClass.Name}.{element.Name}: {newInitialValue} isn't a valid value for {element.Type}"); } } break; case "IsAbstract": { if ((bool)e.NewValue) { modelClass.IsAbstract = true; } } break; case "IsConcurrencyToken": { bool newIsConcurrencyToken = (bool)e.NewValue; if (newIsConcurrencyToken) { element.IsIdentity = false; element.Persistent = true; element.Required = true; element.Type = "Binary"; } } break; case "IsIdentity": { if ((bool)e.NewValue) { if (element.ModelClass.IsDependentType) { if (!modelRoot.IsEFCore5Plus) { errorMessages.Add($"{modelClass.Name}.{element.Name}: Can't make {element.Name} an identity because {modelClass.Name} is a dependent type and can't have an identity property."); } } else { if (!modelRoot.IsValidIdentityAttributeType(element.Type)) { errorMessages.Add($"{modelClass.Name}.{element.Name}: Properties of type {element.Type} can't be used as identity properties."); } else { element.IsConcurrencyToken = false; element.Indexed = true; element.IndexedUnique = true; element.Persistent = true; element.Required = true; if (element.IdentityType == IdentityType.None) { element.IdentityType = IdentityType.AutoGenerated; } } } foreach (Association association in element.ModelClass.LocalNavigationProperties() .Where(nav => nav.AssociationObject.Dependent == element.ModelClass) .Select(nav => nav.AssociationObject) .Where(a => !string.IsNullOrWhiteSpace(a.FKPropertyName) && a.FKPropertyName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Any(n => n.Trim() == element.Name))) { association.GetFKAutoIdentityErrors(); } } else { element.IdentityType = IdentityType.None; } } break; case "MinLength": { int minLengthValue = (int)e.NewValue; if (element.Type != "String") { element.MinLength = 0; } else if (minLengthValue < 0) { errorMessages.Add($"{modelClass.Name}.{element.Name}: MinLength must be zero or a positive number"); } else if (element.MaxLength > 0 && minLengthValue > element.MaxLength) { errorMessages.Add($"{modelClass.Name}.{element.Name}: MinLength cannot be greater than MaxLength"); } } break; case "MaxLength": { if (element.Type != "String") { element.MaxLength = null; } else { int?maxLengthValue = (int?)e.NewValue; if (maxLengthValue > 0 && element.MinLength > maxLengthValue) { errorMessages.Add($"{modelClass.Name}.{element.Name}: MinLength cannot be greater than MaxLength"); } } } break; case "Name": { if (string.IsNullOrEmpty(element.Name) || !CodeGenerator.IsValidLanguageIndependentIdentifier(element.Name)) { errorMessages.Add($"{modelClass.Name}: Property name '{element.Name}' isn't a valid .NET identifier"); } if (modelClass.AllAttributes.Except(new[] { element }).Any(x => x.Name == element.Name) || modelClass.AllNavigationProperties().Any(p => p.PropertyName == element.Name)) { errorMessages.Add($"{modelClass.Name}: Property name '{element.Name}' already in use"); } } break; case "Persistent": { bool newPersistent = (bool)e.NewValue; if (!newPersistent) { element.IsIdentity = false; element.Indexed = false; element.IndexedUnique = false; element.IdentityType = IdentityType.None; element.IsConcurrencyToken = false; element.Virtual = false; } } break; case "ReadOnly": { if (!element.Persistent || element.SetterVisibility != SetterAccessModifier.Public) { element.ReadOnly = false; } } break; case "Required": { bool newRequired = (bool)e.NewValue; if (!newRequired) { if (element.IsIdentity || element.IsConcurrencyToken) { element.Required = true; } } } break; case "Type": { string newType = (string)e.NewValue; if (element.IsIdentity) { if (!modelRoot.IsValidIdentityAttributeType(ModelAttribute.ToCLRType(newType))) { errorMessages.Add($"{modelClass.Name}.{element.Name}: Properties of type {newType} can't be used as identity properties."); } else { element.Required = true; element.Persistent = true; // Change type of any foreign key pointing to this class IEnumerable <Association> participatingAssociations = element.ModelClass.LocalNavigationProperties() .Where(nav => nav.AssociationObject.Dependent == element.ModelClass) .Select(nav => nav.AssociationObject) .Where(a => !string.IsNullOrWhiteSpace(a.FKPropertyName) && a.FKPropertyName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Any(n => n.Trim() == element.Name)); foreach (Association association in participatingAssociations) { AssociationChangedRules.FixupForeignKeys(association); } } } if (newType != "String") { element.MaxLength = null; element.MinLength = 0; element.StringType = HTML5Type.None; } else { if (!element.IsValidInitialValue(newType)) { element.InitialValue = null; } } if (element.IsConcurrencyToken) { element.Type = "Binary"; } if (!element.SupportsInitialValue) { element.InitialValue = null; } } break; } errorMessages = errorMessages.Where(m => m != null).ToList(); if (errorMessages.Any()) { current.Rollback(); ErrorDisplay.Show(store, string.Join("\n", errorMessages)); } }