private static bool Compare(TCollection?a, TCollection?b, ValueComparer <TElement> elementComparer) { if (a is not IReadOnlyList <TElement?> aList) { return(b is not IReadOnlyList <TElement?>); } if (b is not IReadOnlyList <TElement?> bList || aList.Count != bList.Count) { return(false); } if (ReferenceEquals(aList, bList)) { return(true); } for (var i = 0; i < aList.Count; i++) { var(aElement, bElement) = (aList[i], bList[i]); if (aElement is null) { if (bElement is null) { continue; } return(false); } if (bElement is null || !elementComparer.Equals(aElement, bElement)) { return(false); } } return(true); }
private static bool Compare(TElement?[]?a, TElement?[]?b, ValueComparer <TElement> elementComparer) { if (a is null) { return(b is null); } if (b is null || a.Length != b.Length) { return(false); } if (ReferenceEquals(a, b)) { return(true); } for (var i = 0; i < a.Length; i++) { var(aElement, bElement) = (a[i], b[i]); if (aElement is null) { if (bElement is null) { continue; } return(false); } if (bElement is null || !elementComparer.Equals(aElement, bElement)) { return(false); } } return(true); }
/// <summary> /// See <see cref="IIndexable1D.Equals(IIndexable1D, double)"/>. /// </summary> public bool Equals(IIndexable1D other, double tolerance = 1e-13) { if (other is Vector casted) { if (this.Length != other.Length) { return(false); } var comparer = new ValueComparer(tolerance); for (int i = 0; i < Length; ++i) { if (!comparer.AreEqual(this.data[i], casted.data[i])) { return(false); } } return(true); } else { return(other.Equals(this, tolerance)); // To avoid accessing zero entries } }
public static PropertyBuilder <T> HasJsonConversion <T>(this PropertyBuilder <T> propertyBuilder) { ValueConverter <T, string> converter = new ValueConverter <T, string> ( v => JsonConvert.SerializeObject(v), v => JsonConvert.DeserializeObject <T>(v) ); ValueComparer <T> comparer = new ValueComparer <T> ( (l, r) => JsonConvert.SerializeObject(l) == JsonConvert.SerializeObject(r), v => v == null ? 0 : JsonConvert.SerializeObject(v).GetHashCode(), v => JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(v)) ); propertyBuilder.HasConversion(converter); propertyBuilder.Metadata.SetValueConverter(converter); propertyBuilder.Metadata.SetValueComparer(comparer); propertyBuilder.HasColumnType("nvarchar"); propertyBuilder.HasMaxLength(256); return(propertyBuilder); }
/// <summary> /// Initializes a new instance of the <see cref="CoreTypeMapping" /> class. /// </summary> /// <param name="parameters"> The parameters for this mapping. </param> protected CoreTypeMapping(CoreTypeMappingParameters parameters) { Parameters = parameters; var converter = parameters.Converter; var clrType = converter?.ModelClrType ?? parameters.ClrType; ClrType = clrType; if (parameters.Comparer?.Type == clrType) { _comparer = parameters.Comparer; } if (parameters.KeyComparer?.Type == clrType) { _keyComparer = parameters.KeyComparer; } ValueGeneratorFactory = parameters.ValueGeneratorFactory ?? converter?.MappingHints?.ValueGeneratorFactory; }
public static PropertyBuilder <T> HasJsonConversion <T>(this PropertyBuilder <T> propertyBuilder, string fieldName) where T : class, new() { ValueConverter <T, string> converter = new ValueConverter <T, string> ( v => JsonConvert.SerializeObject(v), v => JsonConvert.DeserializeObject <T>(v) ?? new T() ); ValueComparer <T> comparer = new ValueComparer <T> ( (l, r) => JsonConvert.SerializeObject(l) == JsonConvert.SerializeObject(r), v => v == null ? 0 : JsonConvert.SerializeObject(v).GetHashCode(), v => JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(v)) ); propertyBuilder.HasConversion(converter); propertyBuilder.Metadata.SetValueConverter(converter); propertyBuilder.Metadata.SetValueComparer(comparer); propertyBuilder.HasColumnType("longtext"); propertyBuilder.HasField(fieldName); return(propertyBuilder); }
protected override void OnModelCreating(ModelBuilder modelBuilder) { var converter = new ValueConverter <string, string>( v => v, v => v.Trim()); var comparer = new ValueComparer <string>( (l, r) => string.Equals(l, r, StringComparison.OrdinalIgnoreCase), v => v.ToUpper().GetHashCode(), v => v); modelBuilder.Entity <Blog>() .Property(e => e.Id) .HasColumnType("char(20)") .HasConversion(converter, comparer); modelBuilder.Entity <Post>( b => { b.Property(e => e.Id).HasColumnType("char(20)").HasConversion(converter, comparer); b.Property(e => e.BlogId).HasColumnType("char(20)").HasConversion(converter, comparer); }); }
public void Configure(EntityTypeBuilder <Client> builder) { builder.ToTable("Clients"); builder.Property(x => x.ClientId) .ValueGeneratedOnAdd(); builder.HasKey(x => x.ClientId); builder.Property(x => x.Name) .IsRequired() .HasMaxLength(200); var valueComparer = new ValueComparer <List <string> >( (c1, c2) => c1.SequenceEqual(c2), c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), c => c.ToList()); builder.Property(x => x.Scopes) .HasConversion(new JsonValueConverter <List <string> >()) .Metadata .SetValueComparer(valueComparer); builder.Property(x => x.API) .IsRequired() .HasMaxLength(200); builder.Property(x => x.Authority) .IsRequired() .HasMaxLength(200); builder.Property(x => x.CreatedAt) .IsRequired(); builder.Property(x => x.UpdatedAt) .IsRequired(); }
protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity <UserOrder>() .HasKey(uo => new { uo.UserId, uo.OrderId }); var converter = new ValueConverter <IEnumerable <string>, string>( v => JsonConvert.SerializeObject(v), v => JsonConvert.DeserializeObject <IEnumerable <string> >(v) ?? new List <string>()); var comparer = new ValueComparer <IEnumerable <string> >( (l, r) => JsonConvert.SerializeObject(l) == JsonConvert.SerializeObject(r), v => v == null ? 0 : JsonConvert.SerializeObject(v).GetHashCode(), v => JsonConvert.DeserializeObject <IEnumerable <string> >(JsonConvert.SerializeObject(v))); builder.Entity <Order>() .Property(order => order.Products) .HasConversion(converter) .Metadata.SetValueConverter(converter); builder.Entity <Order>() .Property(order => order.Products) .Metadata.SetValueComparer(comparer); builder.Entity <Order>() .Property(order => order.OrderStatus) .HasConversion( status => status.ToString(), status => (Order.OrderStatusEnum)Enum.Parse(typeof(Order.OrderStatusEnum), status)); builder.Entity <Order>() .Property(order => order.OrderType) .HasConversion( orderType => orderType.ToString(), orderType => (Order.OrderTypeEnum)Enum.Parse(typeof(Order.OrderTypeEnum), orderType)); }
private void convertSimulationParameters(Simulation simulation) { var applications = simulation.Model.Root.Container(Constants.APPLICATIONS); if (applications != null) { var allParticleFactors = applications.GetAllChildren <IParameter>(x => x.IsNamed(CoreConstants.Parameters.NUMBER_OF_PARTICLES_FACTOR)); foreach (var allParticleFactor in allParticleFactors) { allParticleFactor.Value *= 1000; } } var allPEndothelialParameters = simulation.Model.Root.GetAllChildren <IParameter>(x => x.IsNamed(ConverterConstants.Parameter.P_endothelial)); foreach (var parameter in allPEndothelialParameters) { if (parameter.Formula.IsExplicit()) { continue; } if (parameter.DefaultValue != null) { continue; } //default value for all P_endotehlial in dm/min parameter.DefaultValue = 10; if (ValueComparer.AreValuesEqual(parameter.DefaultValue.Value, parameter.Value, CoreConstants.DOUBLE_RELATIVE_EPSILON)) { return; } parameter.IsFixedValue = true; } }
private static void validateTimeResults(SimulationResultsImport simulationResultsImport, IndividualResults individualResults) { var time = simulationResultsImport.SimulationResults.Time; int expectedLength = time.Values.Length; int currentLength = individualResults.Time.Values.Length; if (time.Values.Length != individualResults.Time.Values.Length) { simulationResultsImport.AddError(PKSimConstants.Error.TimeArrayLengthDoesNotMatchFirstIndividual(individualResults.IndividualId, expectedLength, currentLength)); return; } for (int i = 0; i < currentLength; i++) { if (!ValueComparer.AreValuesEqual(time[i], individualResults.Time[i])) { simulationResultsImport.AddError(PKSimConstants.Error.TimeArrayValuesDoesNotMatchFirstIndividual(individualResults.IndividualId, i, time[i], individualResults.Time[i])); } } //update reference time to ensure that all results are using the same time individualResults.Time = time; individualResults.UpdateQuantityTimeReference(); }
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity <Question>().Property(p => p.IncorrectAnswers).HasConversion( v => JsonConvert.SerializeObject(v), v => JsonConvert.DeserializeObject <List <string> >(v)); var valueComparer = new ValueComparer <List <string> >( (c1, c2) => c1.SequenceEqual(c2), c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), c => c.ToList()); modelBuilder .Entity <Question>() .Property(e => e.IncorrectAnswers) .Metadata .SetValueComparer(valueComparer); modelBuilder.Entity <Difficulty>().HasData(new Difficulty { DifficultyId = 1, DifficultyName = "Easy", Description = "easy" }); modelBuilder.Entity <Difficulty>().HasData(new Difficulty { DifficultyId = 2, DifficultyName = "Medium", Description = "medium" }); modelBuilder.Entity <Difficulty>().HasData(new Difficulty { DifficultyId = 3, DifficultyName = "Hard", Description = "hard" }); modelBuilder.Entity <Type>().HasData(new Type { TypeId = 1, TypeName = "Multiple Choice", Description = "multiple" }); modelBuilder.Entity <Type>().HasData(new Type { TypeId = 2, TypeName = "True / False", Description = "boolean" }); }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SqlServerUdtTypeMapping( [NotNull] Type clrType, [NotNull] string storeType, [NotNull] Func <object, Expression> literalGenerator, StoreTypePostfix storeTypePostfix = StoreTypePostfix.None, [CanBeNull] string udtTypeName = null, [CanBeNull] ValueConverter converter = null, [CanBeNull] ValueComparer comparer = null, [CanBeNull] ValueComparer keyComparer = null, DbType?dbType = null, bool unicode = false, int?size = null, bool fixedLength = false, int?precision = null, int?scale = null) : base( new RelationalTypeMappingParameters( new CoreTypeMappingParameters( clrType, converter, comparer, keyComparer), storeType, storeTypePostfix, dbType, unicode, size, fixedLength, precision, scale)) { LiteralGenerator = literalGenerator; UdtTypeName = udtTypeName ?? storeType; }
/// <summary> /// Make the conversion between enum array and string. /// </summary> /// <typeparam name="TEnum">Enum with string name and value in Int32.</typeparam> /// <param name="propertyBuilder"></param> /// <returns></returns> public static PropertyBuilder <TEnum[]> HasEnumArrayConversion <TEnum>(this PropertyBuilder <TEnum[]> propertyBuilder) where TEnum : Enum { var type = typeof(TEnum); if (type.IsEnum) { var valueConverter = new ValueConverter <TEnum[], string>( x => string.Join(',', x.Select(y => Convert.ToInt32(Enum.ToObject(type, y)).ToString())), x => x.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(y => (TEnum)Enum.Parse(type, y)).ToArray()); var valueComparer = new ValueComparer <TEnum[]>( (c1, c2) => c1.SequenceEqual(c2), c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), c => c.ToArray()); propertyBuilder.HasConversion(valueConverter); propertyBuilder.Metadata.SetValueComparer(valueComparer); return(propertyBuilder); } throw new ArgumentException("Generic parameter has to be enum type."); }
private static bool Compare(TElem[]?a, TElem[]?b, ValueComparer <TElem> elementComparer) { if (a is null) { return(b is null); } if (b is null || a.Length != b.Length) { return(false); } // Note: the following currently boxes every element access because ValueComparer isn't really // generic (see https://github.com/aspnet/EntityFrameworkCore/issues/11072) for (var i = 0; i < a.Length; i++) { if (!elementComparer.Equals(a[i], b[i])) { return(false); } } return(true); }
public static PropertyBuilder <T> HasJsonConversion <T>(this PropertyBuilder <T> propertyBuilder, JsonSerializerOptions?jsonSerializerOptions = null) { var options = jsonSerializerOptions ?? defaultJsonSerializerOptions; var converter = new ValueConverter <T, string> ( v => JsonSerializer.Serialize(v, options), v => JsonSerializer.Deserialize <T>(v, options) ); var comparer = new ValueComparer <T> ( (l, r) => JsonSerializer.Serialize(l, options) == JsonSerializer.Serialize(r, options), v => v == null ? 0 : JsonSerializer.Serialize(v, options).GetHashCode(), v => JsonSerializer.Deserialize <T>(JsonSerializer.Serialize(v, options), options) ); propertyBuilder.HasConversion(converter); propertyBuilder.Metadata.SetValueConverter(converter); propertyBuilder.Metadata.SetValueComparer(comparer); propertyBuilder.HasColumnType("nvarchar(MAX)"); return(propertyBuilder); }
public static void IsDocumentBacked <T, U>(this EntityTypeBuilder <T> builder) where T : DocumentBacked <U> where U : class, new() { ValueConverter <U, string> converter = new ValueConverter <U, string> ( v => JsonSerializer.Serialize(v, null), v => JsonSerializer.Deserialize <U>(v, null) ?? new U() ); ValueComparer <U> comparer = new ValueComparer <U> ( (l, r) => JsonSerializer.Serialize(l, null) == JsonSerializer.Serialize(r, null), v => v == null ? 0 : JsonSerializer.Serialize(v, null).GetHashCode(), v => JsonSerializer.Deserialize <U>(JsonSerializer.Serialize(v, null), null) ); var propertyBuilder = builder.Property(db => db.Document); propertyBuilder.HasConversion(converter); propertyBuilder.Metadata.SetValueConverter(converter); propertyBuilder.Metadata.SetValueComparer(comparer); propertyBuilder.HasColumnType("nvarchar(max)"); }
Logger = LoggerFactory.Create(x => x.AddConsole()); //.SetMinimumLevel(LogLevel.Debug)); protected override void OnModelCreating(ModelBuilder modelBuilder) { #region ConfigureListProperty modelBuilder .Entity <EntityType>() .Property(e => e.MyProperty) .HasConversion( v => JsonSerializer.Serialize(v, null), v => JsonSerializer.Deserialize <List <int> >(v, null)); #endregion #region ConfigureListPropertyComparer var valueComparer = new ValueComparer <List <int> >( (c1, c2) => c1.SequenceEqual(c2), c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), c => c.ToList()); modelBuilder .Entity <EntityType>() .Property(e => e.MyProperty) .Metadata .SetValueComparer(valueComparer); #endregion }
public override async Task <IParameter> MapToModel(SnapshotParameter snapshot, IParameter parameter) { _valueOriginMapper.UpdateValueOrigin(parameter.ValueOrigin, snapshot.ValueOrigin); //only update formula if required if (snapshot.TableFormula != null) { parameter.Formula = await _tableFormulaMapper.MapToModel(snapshot.TableFormula); } if (snapshot.Value == null) { return(parameter); } var displayUnit = ModelValueFor(snapshot.Unit); if (!parameter.Dimension.HasUnit(displayUnit)) { _logger.AddWarning(PKSimConstants.Warning.UnitNotFoundInDimensionForParameter(displayUnit, parameter.Dimension.Name, parameter.Name)); } parameter.DisplayUnit = parameter.Dimension.UnitOrDefault(displayUnit); //This needs to come AFTER formula update so that the base value is accurate var baseValue = parameter.Value; var snapshotValueInBaseUnit = parameter.ConvertToBaseUnit(snapshot.Value); if (!ValueComparer.AreValuesEqual(baseValue, snapshotValueInBaseUnit)) { parameter.Value = snapshotValueInBaseUnit; parameter.IsDefault = false; } return(parameter); }
public bool Evaluate(Record r, SubRecord sr, Element se) { if (se == null) { return(false); } var value = sr.GetCompareValue(se); int diff = ValueComparer.Compare(value, this.Value); switch (this.Type) { case BatchCondElementType.Set: break; case BatchCondElementType.Add: break; case BatchCondElementType.Subtract: break; case BatchCondElementType.Multiply: break; case BatchCondElementType.Divide: break; case BatchCondElementType.Clear: break; default: throw new ArgumentOutOfRangeException(); } return(false); }
public void Configure(EntityTypeBuilder <Organisation> builder) { builder.HasKey(e => e.Id); builder.Property(e => e.Name).IsRequired(); builder.Property(e => e.Description).IsRequired(); var splitStringConverter = new ValueConverter <List <string>, string>(v => string.Join(";", v), v => string.IsNullOrEmpty(v) ? new List <string>() : v.Split(new[] { ';' }).ToList()); var valueComparer = new ValueComparer <List <string> >( (c1, c2) => c1.SequenceEqual(c2), c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), c => c.ToList()); builder .Property(e => e.Classifications) .IsRequired() .HasConversion(splitStringConverter) .Metadata .SetValueComparer(valueComparer); builder.Property(e => e.Address).IsRequired(); builder.Property(e => e.Status).IsRequired(); builder.HasData( new Organisation { Id = 1, Name = "Topiver", Classifications = new List <string> { "Trading", "C++" }, Address = "39 Hunter St, Sydney NSW 2000, Australia", Status = OrganisationStatus.Active, Description = "Topiver is a proprietary trading firm and market maker for various exchange-listed financial instruments. Its name derives from the Dutch optie verhandelaar, or \"option trader\"." }, new Organisation { Id = 2, Name = "Fletnix", Classifications = new List <string> { "Streaming", "Java", "JavaScript" }, Address = "Fletnix Corporate Headquarters 100 Winchester Circle Los Gatos, CA 95032,", Status = OrganisationStatus.Active, Description = "Fletnix, Inc. is an American technology and media services provider and production company headquartered in Los Gatos, California. Fletnix was founded in 1997 by Reed Hastings and Marc Randolph in Scotts Valley, California." }, new Organisation { Id = 3, Name = "Aslattian", Classifications = new List <string> { "Java", "React", "AWS" }, Address = "6/341 George St, Sydney NSW 2000, Australia", Status = OrganisationStatus.Inactive, Description = "Aslattian Corporation Plc is an Australian software company that develops products for software developers and project managers." } ); }
public static void SetStructuralValueComparer( [NotNull] this IConventionProperty property, [CanBeNull] ValueComparer comparer, bool fromDataAnnotation = false) => property.SetKeyValueComparer(comparer, fromDataAnnotation);
/// <summary> /// Sets the custom <see cref="ValueComparer" /> for this property when performing key comparisons. /// </summary> /// <param name="property"> The property. </param> /// <param name="comparer"> The comparer, or <c>null</c> to remove any previously set comparer. </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> public static void SetKeyValueComparer( [NotNull] this IConventionProperty property, [CanBeNull] ValueComparer comparer, bool fromDataAnnotation = false) => property.AsProperty().SetKeyValueComparer( comparer, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
private bool areValuesEqual(IParameter targetParameter, IParameter sourceParameter) { return(ValueComparer.AreValuesEqual(targetParameter, sourceParameter)); }
bool IConventionPropertyBuilder.CanSetStructuralValueComparer(ValueComparer comparer, bool fromDataAnnotation) => CanSetStructuralValueComparer( comparer, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
IConventionPropertyBuilder IConventionPropertyBuilder.HasKeyValueComparer(ValueComparer comparer, bool fromDataAnnotation) => HasKeyValueComparer(comparer, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanSetStructuralValueComparer([CanBeNull] ValueComparer comparer, ConfigurationSource?configurationSource) => (configurationSource.Overrides(Metadata.GetStructuralValueComparerConfigurationSource()) && Metadata.CheckValueComparer(comparer) == null) || Metadata.GetStructuralValueComparer() == comparer;
private static object SnapshotValue(ValueComparer comparer, object value) => comparer == null ? value : comparer.Snapshot(value);
private static object SnapshotValue(IProperty property, ValueComparer comparer, IUpdateEntry entry) => SnapshotValue(comparer, entry.GetCurrentValue(property));
/// <summary> /// Configures the property so that the property value is converted to and from the database /// using the given <see cref="ValueConverter" />. /// </summary> /// <param name="converter"> The converter to use. </param> /// <param name="valueComparer"> The comparer to use for values before conversion. </param> /// <returns> The same builder instance so that multiple configuration calls can be chained. </returns> public virtual PropertyBuilder HasConversion([CanBeNull] ValueConverter converter, [CanBeNull] ValueComparer valueComparer) { Builder.HasConversion(converter, ConfigurationSource.Explicit); Builder.HasValueComparer(valueComparer, ConfigurationSource.Explicit); return(this); }