private static DbPropertyValues MergeValues(DbPropertyValues original, DbPropertyValues current, DbPropertyValues database) { var result = original.Clone(); foreach (var propertyName in original.PropertyNames) { if (original[propertyName] is DbPropertyValues) { var mergedComplexValues = MergeValues( (DbPropertyValues)original[propertyName], (DbPropertyValues)current[propertyName], (DbPropertyValues)database[propertyName]); ((DbPropertyValues)result[propertyName]) .SetValues(mergedComplexValues); } else { if (!object.Equals( current[propertyName], original[propertyName])) { result[propertyName] = current[propertyName]; } else if (!object.Equals( database[propertyName], original[propertyName])) { result[propertyName] = database[propertyName]; } } } return(result); }
public static DbEntityEntry Refresh(this DbEntityEntry tracking, RefreshConflict refreshMode) { tracking.NotNull(nameof(tracking)); switch (refreshMode) { case RefreshConflict.StoreWins: { // When entity is already deleted in database, Reload sets tracking state to Detached. // When entity is already updated in database, Reload sets tracking state to Unchanged. tracking.Reload(); // Execute SELECT. // Hereafter, SaveChanges ignores this entity. break; } case RefreshConflict.ClientWins: { DbPropertyValues databaseValues = tracking.GetDatabaseValues(); // Execute SELECT. if (databaseValues == null) { // When entity is already deleted in database, there is nothing for client to win against. // Manually set tracking state to Detached. tracking.State = EntityState.Detached; // Hereafter, SaveChanges ignores this entity. } else { // When entity is already updated in database, refresh original values, which go to in WHERE clause. tracking.OriginalValues.SetValues(databaseValues); // Hereafter, SaveChanges executes UPDATE/DELETE for this entity, with refreshed values in WHERE clause. } break; } case RefreshConflict.MergeClinetAndStore: { DbPropertyValues databaseValues = tracking.GetDatabaseValues(); // Execute SELECT. if (databaseValues == null) { // When entity is already deleted in database, there is nothing for client to merge with. // Manually set tracking state to Detached. tracking.State = EntityState.Detached; // Hereafter, SaveChanges ignores this entity. } else { // When entity is already updated, refresh original values, which go to WHERE clause. DbPropertyValues originalValues = tracking.OriginalValues.Clone(); tracking.OriginalValues.SetValues(databaseValues); // If database has an different value for a property, then retain the database value. databaseValues.PropertyNames // Navigation properties are not included. .Where(property => !object.Equals(originalValues[property], databaseValues[property])) .ForEach(property => tracking.Property(property).IsModified = false); // Hereafter, SaveChanges executes UPDATE/DELETE for this entity, with refreshed values in WHERE clause. } break; } } return(tracking); }
private static void AddHistoricalEntity(DbContext dbContext, DbPropertyValues originalValues, DateTimeOffset moment) { var original = Mapper.Map <THistoricalEntity>(originalValues.ToObject()); original.ValidTo = moment; dbContext.Set <THistoricalEntity>().Add(original); }
public void HaveUserResolveConcurrency(DbPropertyValues currentValues, DbPropertyValues databaseValues, DbPropertyValues resolvedValues) { currentValues.GetValue <Article>("ArticleId"); resolvedValues.SetValues(db.Articles.Find().Name); }
public static void ShowValues(DbPropertyValues values) { foreach (var propertyName in values.PropertyNames) { Console.WriteLine($"{propertyName} has value {values[propertyName]}"); } }
private static T InnerGetCopy <T>(IDbContext context, T currentCopy, Func <DbEntityEntry <T>, DbPropertyValues> func) where T : BaseEntity { //Get the database context //获取数据库上下文 DbContext dbContext = CastOrThrow(context); //Get the entity tracking object //获取实体跟踪对象 DbEntityEntry <T> entry = GetEntityOrReturnNull(currentCopy, dbContext); //The output //输出 T output = null; //Try and get the values //尝试得到这些值 if (entry != null) { DbPropertyValues dbPropertyValues = func(entry); if (dbPropertyValues != null) { output = dbPropertyValues.ToObject() as T; } } return(output); }
private string GetEntryValueInString(DbEntityEntry entry, bool isOrginal) { XDocument document = new XDocument(); try { IEnumerable <string> PropertyNames = new List <string>(); object target = Constants.CloneEntity((Object)entry.Entity); DbPropertyValues dbValues = null; if (isOrginal) { PropertyNames = entry.OriginalValues.PropertyNames; dbValues = entry.GetDatabaseValues(); if (dbValues == null) { return(""); } } else { PropertyNames = entry.CurrentValues.PropertyNames; } foreach (var propertyName in PropertyNames) { object setterValue = null; if (isOrginal) { //Get orginal value setterValue = dbValues[propertyName]; } else { //Get orginal value setterValue = entry.CurrentValues[propertyName]; } PropertyInfo propInfo = target.GetType().GetProperty(propertyName); //update property with orgibal value if (setterValue == DBNull.Value) {// setterValue = null; } propInfo.SetValue(target, setterValue, null); }//end foreach //XmlSerializer formatter = new XmlSerializer(target.GetType()); var formatter = new DataContractSerializer(target.GetType()); using (XmlWriter xmlWriter = document.CreateWriter()) { formatter.WriteObject(xmlWriter, target); } } catch (Exception ex) { // this.logger.Error("GetEntryValueInString", ex); throw ex; } return(document.Root.ToString()); }
static public void PrintProp(DbPropertyValues prop) { foreach (var values in prop.PropertyNames) { Console.WriteLine("{0} : {1} ", values, prop[values]); } }
public AuditEntry(object auditableEntity, DbPropertyValues current, DbPropertyValues original) { if (auditableEntity is Template) { SetPropeties(auditableEntity as Template); } else if (auditableEntity is TemplateConstraint) { SetPropeties(auditableEntity as TemplateConstraint); } else if (auditableEntity is ImplementationGuide) { SetProperties(auditableEntity as ImplementationGuide); } else if (auditableEntity is ValueSet) { SetProperties(auditableEntity as ValueSet); } else if (auditableEntity is ValueSetMember) { SetProperties(auditableEntity as ValueSetMember); } else if (auditableEntity is CodeSystem) { SetProperties(auditableEntity as CodeSystem); } SetProperties(current, original); }
private object GetFieldValue(string name, DbPropertyValues values) { var val = values[name]; return(val == null ? "null" : (IsNumber(val) ? val.ToString() : $@"""{val}""")); }
/// <summary> /// Conviernte una colección recibida en un objeto TEntity /// /// /// Nota: Los parámetros no incluidos se escriben en la consola /// </summary> /// <param name="tipo">Tipo de objeto que se desea convertir</param> /// <param name="values">Coleccion recibida</param> /// <returns>Instancia al objeto con los valores recibidos</returns> protected internal object DbPropertyValuesToModel(Type tipo, DbPropertyValues values) { var entityObject = Activator.CreateInstance(tipo); /* PropertyInfo[] properties = tipo.GetProperties(); * * foreach (PropertyInfo property in properties) * { * try * { * if (propertyInfo != null) * { * var value = values.g * property.SetValue(entityObject, value, null); * } * else * { * Debugger.Log(0, "ConvertFormCollection WARNING", "Property No Found in Model: " + key); * } * } * catch (Exception ex) * { * Debugger.Log(0, "ConvertFormCollection WARNING", ex.Message); * } * }*/ return(entityObject); }
public void Select() { HuNiEntities huni = new HuNiEntities(); //基于表达式的查询语法 using (var edm = new HuNiEntities()) { string esql = "select value c from NorthwindEntities.Customers as c order by c.CustomerID limit 10"; //ObjectQuery<Teacher> objectQuery = edm.CreateQuery<Teacher>(esql); ObjectContext context = new ObjectContext("sql"); ObjectQuery <Teacher> customers = new ObjectQuery <Teacher>(esql, context); IQueryable <Teacher> cust1 = from c in customers select c; //使用ObjectQuery类的ToTraceString()方法显示查询SQL语句 customers.ToTraceString(); } using (var edm = new EmptyModelContainer()) { Teacher teacher = edm.Set <Teacher>().Find(3); Student arti = teacher.Student.ToList().Find(o => o.ID == 2); //取当前值 DbPropertyValues currentValues = edm.Entry <Teacher>(teacher).CurrentValues; //取原值 DbPropertyValues originalValues = edm.Entry <Teacher>(teacher).OriginalValues; //取数据库值 DbPropertyValues databaseValues = edm.Entry <Teacher>(teacher).GetDatabaseValues(); } }
private void PrintPropertyValues( DbPropertyValues values, IEnumerable <string> propertiesToPrint, int indent = 1) { foreach (var propertyName in propertiesToPrint) { var value = values[propertyName]; if (value is DbPropertyValues) { Console.WriteLine( "{0}- Complex Property: {1}", string.Empty.PadLeft(indent), propertyName); var complexPropertyValues = (DbPropertyValues)value; PrintPropertyValues( complexPropertyValues, complexPropertyValues.PropertyNames, indent + 1); } else { Console.WriteLine( "{0}- {1}: {2}", string.Empty.PadLeft(indent), propertyName, values[propertyName]); } } }
public static void DisplayDBPropertyValues(string label, DbPropertyValues currentValues, DbPropertyValues originalValues, int indent = 1) { Console.WriteLine(label + ":"); foreach (string name in currentValues.PropertyNames) { var currentValue = currentValues[name]; if (currentValue is DbPropertyValues) { Console.WriteLine("{0}- complex property {1}", String.Empty.PadLeft(indent), name); DisplayDBPropertyValues((DbPropertyValues)currentValue, null, indent + 1); } else { if (originalValues == null) { Console.WriteLine("{0}- {1}:\t{2}", String.Empty.PadLeft(indent), name, currentValue); } else { var originalValue = originalValues[name]; Console.WriteLine("{0}- {1}:\t{2}\t[{3}]", String.Empty.PadLeft(indent), name, currentValue, originalValue); } } } }
static public List <LogProperty> GetLogProperties(Type modelType, DbPropertyValues values, DbContext context) { var list = new List <LogProperty>(); PropertyInfo[] properties = modelType.GetProperties(); foreach (PropertyInfo pi in properties) { if (pi.GetGetMethod().IsVirtual || pi.HasAttribute <NotMappedAttribute>()) { continue; } string value = values[pi.Name] == null ? "null" : values[pi.Name].ToString(); list.Add(new LogProperty(pi.Name, value)); } FetchForeignKeyValues(modelType, context, list); // Order of PropertyInfo[] might be random, which might cause troubles in detecting differences list.Sort((a, b) => string.Compare(a.name, b.name)); return(list); }
private static void PrintPropertyValues(DbPropertyValues values) { foreach (var propertyName in values.PropertyNames) { Console.WriteLine(" - {0}: {1}", propertyName, values[propertyName]); } }
private static void builLog(List <string> logText, DbPropertyValues originalValues, DbPropertyValues currentValues, string container = null) { foreach (string pname in originalValues.PropertyNames) { var originalValue = originalValues[pname]; var currentValue = currentValues[pname]; if (!(originalValue == null && currentValue == null)) { string origString = getStringValue(originalValue); string currentString = getStringValue(currentValue); if (!string.Equals(origString, currentString)) { string log; if (container != null) { log = $"{container}.{pname}: [{origString}] to [{currentString}]"; } else { log = $"{pname}: [{origString}] to [{currentString}]"; } logText.Add(log); } } } }
/// <summary> /// Detects any updates on specified entity and tracks them via AlertManager.TrackablePropertyUpdated alert. /// </summary> /// <param name="entity">entity</param> /// <param name="originalValues">original properties values</param> /// <param name="currentValues">current properties values</param> /// <param name="properties">properties to track</param> /// <param name="updateCallback">action to call when update is detected. If it is null it defaults to AlertManager.TrackablePropertyChanged.</param> /// <remarks> /// This method would likely be called from <see cref="IModifyHook.OnModify">OnModify</see> implementation to track properties. /// For tracking enum typed (state) properties see <see cref="DetectStateUpdates">DetectStateUpdates</see> method. /// </remarks> public static void DetectUpdates(this IBaseDO entity, DbPropertyValues originalValues, DbPropertyValues currentValues, PropertyInfo[] properties, Action<string, object, PropertyInfo> updateCallback = null) { if (properties == null || properties.Length == 0) return; if (updateCallback == null) { updateCallback = (entityName, idValue, property) => AlertManager.TrackablePropertyUpdated(entityName, property.Name, idValue, currentValues[property.Name]); } var type = entity.GetType(); var idProperty = type.GetProperty("Id"); var id = idProperty != null ? idProperty.GetValue(entity) : null; foreach (var property in properties) { if (!MiscUtils.AreEqual(originalValues[property.Name], currentValues[property.Name])) { string entityName; if (type.Name.EndsWith("DO", StringComparison.Ordinal)) entityName = type.Name.Remove(type.Name.Length - 2); else if (type.BaseType != null && type.BaseType.Name.EndsWith("DO", StringComparison.Ordinal)) entityName = type.BaseType.Name.Remove(type.BaseType.Name.Length - 2); else entityName = type.Name; updateCallback(entityName, id, property); } } }
private void HaveUserResolveConcurrency(DbPropertyValues currentValues, DbPropertyValues databaseValues, DbPropertyValues resolvedValues) { // Show the current, database, and resolved values to the user and have // them edit the resolved values to get the correct resolution. }
public object this[string propertyName] { get { return(this.GetItem(propertyName).Value); } set { DbPropertyValues dbPropertyValues = value as DbPropertyValues; if (dbPropertyValues != null) { value = (object)dbPropertyValues.InternalPropertyValues; } IPropertyValuesItem propertyValuesItem = this.GetItem(propertyName); InternalPropertyValues internalPropertyValues = propertyValuesItem.Value as InternalPropertyValues; if (internalPropertyValues == null) { this.SetValue(propertyValuesItem, value); } else { InternalPropertyValues values = value as InternalPropertyValues; if (values == null) { throw Error.DbPropertyValues_AttemptToSetNonValuesOnComplexProperty(); } internalPropertyValues.SetValues(values); } } }
private void SetDeletedProperties(DbEntityEntry entry, StringBuilder oldData, StringBuilder TokenId, StringBuilder UserId) { DbPropertyValues dbValues = entry.GetDatabaseValues(); foreach (var propertyName in dbValues.PropertyNames) { var oldVal = dbValues[propertyName]; oldData.AppendFormat("{0}={1} || ", propertyName, oldVal ?? ""); if (oldVal != null) { if (propertyName == "LastUpdatedBy" || propertyName == "UpdatedBy") { Guid gUserId = Guid.Empty; if (Guid.TryParse(oldVal.ToString(), out gUserId)) { //var Token = context.TokenMasters.Where(o => o.UserId == gUserId).FirstOrDefault(); //if (Token != null) //{ // TokenId.Append(Token.AuthToken); //} UserId.Append(gUserId.ToString()); } } } } if (oldData.Length > 0) { oldData = oldData.Remove(oldData.Length - 3, 3); } }
private static void AskUser(DbPropertyValues currentValues, DbPropertyValues databaseValues, DbPropertyValues resolvedValues) { foreach (string propertyName in currentValues.PropertyNames) { Console.WriteLine("{0}, current: {1}, database: {2}, proposed: {3}", propertyName, currentValues[propertyName], databaseValues[propertyName], resolvedValues[propertyName]); } }
public static List <String> rastreaCambios(Object modeloEditado, DbPropertyValues valoresAnteriores) { List <String> listaCambios = new List <string>(); var atributosObjetoEditado = modeloEditado.GetType().GetProperties().ToList(); //Recorre los atributos del objeto editado foreach (var itemObjetoEditado in atributosObjetoEditado) { var valorActual = itemObjetoEditado.GetValue(modeloEditado, null);//valor del atributo if (valorActual == null) { valorActual = ""; } if (valoresAnteriores.PropertyNames.ToArray().Contains(itemObjetoEditado.Name)) { var valorAnterior = valoresAnteriores[itemObjetoEditado.Name]; if (valorAnterior == null) { valorAnterior = ""; } if (valorAnterior.ToString() != valorActual.ToString()) { String displayNameAtributo = ""; try { displayNameAtributo = itemObjetoEditado.GetCustomAttribute <System.ComponentModel.DisplayNameAttribute>().DisplayName;//nombre del atributo } catch (Exception e) { Console.WriteLine(e.Message); displayNameAtributo = ""; } if (displayNameAtributo == null || displayNameAtributo.ToString().Trim() == "") { displayNameAtributo = itemObjetoEditado.Name; } if (valorAnterior == null || valorAnterior.ToString() == "") { valorAnterior = "[Vacío]"; } if (valorActual == null || valorActual.ToString() == "") { valorActual = "[Vacío]"; } listaCambios.Add("- " + displayNameAtributo); listaCambios.Add(" Anterior: " + valorAnterior); listaCambios.Add(" Nuevo: " + valorActual); } } } if (listaCambios.Count > 0) { listaCambios.Insert(0, "Atributos modificados:"); } return(listaCambios); }
static object GetComplexPropertyValue(DbPropertyValues propertyValues, string[] propertyChain) { var propertyName = propertyChain.First(); return(propertyChain.Length == 1 ? propertyValues[propertyName] : GetComplexPropertyValue((DbPropertyValues)propertyValues[propertyName], propertyChain.Skip(1).ToArray())); }
private void LogEventContainerStateChanged(DbPropertyValues currentValues) { var uow = ObjectFactory.GetInstance <IUnitOfWork>(); //In the GetByKey I make use of dictionary datatype: https://msdn.microsoft.com/en-us/data/jj592677.aspx var curContainerDO = uow.ContainerRepository.GetByKey(currentValues[currentValues.PropertyNames.First()]); CreateContainerFact(curContainerDO, "StateChanged"); }
public static void PrintValues(DbPropertyValues values) { foreach (var propertyName in values.PropertyNames) { Console.WriteLine("Property {0} has value {1}", propertyName, values[propertyName]); } }
internal static void ContainerStateChanged(DbPropertyValues currentValues) { var handler = EventContainerStateChanged; if (handler != null) { handler(currentValues); } }
public DbEntityPropertyValues(DbPropertyValues dbPropertyValues) { IEnumerable <string> dbPropertyNames = dbPropertyValues.PropertyNames; foreach (var prop in dbPropertyNames) { entityKeyValuePairs.Add(prop, dbPropertyValues.GetValue <Object>(prop)); } }
public void Non_Generic_DbPropertyValues_uses_ToObject_on_InternalPropertyValues() { var properties = new Dictionary<string, object> { { "Id", 1 } }; var values = new DbPropertyValues(new TestInternalPropertyValues<FakeTypeWithProps>(properties)); var clone = (FakeTypeWithProps)values.ToObject(); Assert.Equal(1, clone.Id); }
public string GetOldEntityJson(T entity) { DbPropertyValues current = DbContext.Entry(entity).CurrentValues.Clone(); DbContext.Entry(entity).Reload(); string oldEntity = entity.ToJson(); DbContext.Entry(entity).CurrentValues.SetValues(current); return oldEntity; }
public EntityFrameworkDbPropertyValues(DbPropertyValues wrappedValues) { if (wrappedValues == null) { throw new ArgumentNullException("wrappedValues"); } _wrappedValues = wrappedValues; }
private void buttonSave_Click(object sender, RoutedEventArgs e) { try { int effected = 0; DbChangeTracker tracker = entity.ChangeTracker; IEnumerable <DbEntityEntry> entries = tracker.Entries(); Console.WriteLine(entity.Employees.Count()); //dataGrid.ItemsSource = entries.ToList(); if (tracker.HasChanges()) { IEnumerable <DbEntityEntry> modifiedEntries = entries.Where(n => n.State == System.Data.Entity.EntityState.Modified); List <Employee> changes = new List <Employee>(); foreach (DbEntityEntry entityEntry in modifiedEntries) { //DbPropertyValues oldValues = entityEntry.GetDatabaseValues(); DbPropertyValues newValues = entityEntry.CurrentValues; Employee employee = (Employee)newValues.ToObject(); changes.Add(employee); } IEnumerable <DbEntityEntry> deletedEntries = entries.Where(n => n.State == System.Data.Entity.EntityState.Deleted || n.State == System.Data.Entity.EntityState.Detached); List <Employee> deletes = new List <Employee>(); foreach (DbEntityEntry entityEntry in deletedEntries) { //DbPropertyValues oldValues = entityEntry.GetDatabaseValues(); DbPropertyValues newValues = entityEntry.CurrentValues; Employee employee = (Employee)newValues.ToObject(); deletes.Add(employee); } IEnumerable <DbEntityEntry> addedEntries = entries.Where(n => n.State == System.Data.Entity.EntityState.Added); List <Employee> adds = new List <Employee>(); foreach (DbEntityEntry entityEntry in addedEntries) { //DbPropertyValues oldValues = entityEntry.GetDatabaseValues(); DbPropertyValues newValues = entityEntry.CurrentValues; Employee employee = (Employee)newValues.ToObject(); adds.Add(employee); } ItemChanges itemChanges = new ItemChanges(); itemChanges.Topmost = true; itemChanges.dataGridChanges.ItemsSource = changes.ToList(); itemChanges.dataGridChangesDelete.ItemsSource = deletes.ToList(); itemChanges.dataGridChangesNew.ItemsSource = adds.ToList(); itemChanges.ShowDialog(); if (itemChanges.IsAccepted) { effected = entity.SaveChanges(); MessageBox.Show("Success to update data: " + effected.ToString() + " item(s)."); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public override void OnModify(DbPropertyValues originalValues, DbPropertyValues currentValues) { base.OnModify(originalValues, currentValues); var reflectionHelper = new ReflectionHelper<IncidentDO>(); var priorityPropertyName = reflectionHelper.GetPropertyName(i => i.Priority); if (!MiscUtils.AreEqual(originalValues[priorityPropertyName], currentValues[priorityPropertyName]) && IsHighPriority) { AlertManager.HighPriorityIncidentCreated(Id); } }
/// <summary> /// 记录帮助类 /// </summary> private void PrintPropertyValues(DbPropertyValues values, IEnumerable<string> propertiesToPrint, int indent = 1) { foreach (var propertyName in propertiesToPrint) { var value = values[propertyName]; if (value is DbPropertyValues) { Console.WriteLine("{0}- Complex Property: {1}", string.Empty.PadLeft(indent), propertyName); var complexPropertyValues = (DbPropertyValues)value; PrintPropertyValues(complexPropertyValues, complexPropertyValues.PropertyNames, indent + 1); } else { Console.WriteLine("{0}- {1}: {2}", string.Empty.PadLeft(indent), propertyName, values[propertyName]); } } }
public static void WritePropertyValues(DbPropertyValues values, int indent = 1) { foreach (string propertyName in values.PropertyNames) { var value = values[propertyName]; if (value is DbPropertyValues) { Console.WriteLine("{0} - Complex Property: {1}", string.Empty.PadLeft(indent), propertyName); WritePropertyValues((DbPropertyValues)value, indent + 1); } else { Console.WriteLine("{0} - {1}: {2}", string.Empty.PadLeft(indent), propertyName,values[propertyName]); } } }
/// <summary> /// Detects any updates on specified entity state properties. /// </summary> /// <param name="entity">entity</param> /// <param name="originalValues">original properties values</param> /// <param name="currentValues">current properties values</param> public static void DetectStateUpdates(this IBaseDO entity, DbPropertyValues originalValues, DbPropertyValues currentValues) { var stateProperties = entity.GetStateProperties().ToArray(); if (stateProperties.Length > 0) { entity.DetectUpdates(originalValues, currentValues, stateProperties, (entityName, idValue, stateProperty) => { var stateTemplateType = ReflectionHelper.ForeignKeyNavitationProperty(entity, stateProperty). PropertyType; var stateType = GetGenericInterface(stateTemplateType, typeof (IStateTemplate<>)) .GetGenericArguments()[0]; var stateName = stateType.Name; var stateKey = currentValues[stateProperty.Name]; var stateValue = stateKey != null ? stateType.GetFields().Single(f => Equals(f.GetValue(entity), stateKey)).Name : null; AlertManager.EntityStateChanged(entityName, idValue, stateName, stateValue); }); } }
private void AsssertProperties(DbPropertyValues originalValues) { IEnumerable<String> properties = originalValues.PropertyNames; IEnumerator<LoggableProperty> actual = new LoggableEntity(entry).Properties.GetEnumerator(); IEnumerator<LoggableProperty> expected = properties.Where(property => property != "Id") .Select(name => new LoggableProperty(entry.Property(name), originalValues[name])).GetEnumerator(); while (expected.MoveNext() | actual.MoveNext()) { Assert.Equal(expected.Current.IsModified, actual.Current.IsModified); Assert.Equal(expected.Current.ToString(), actual.Current.ToString()); } }
private void HaveUserResolveConcurrency(DbPropertyValues currentValues, DbPropertyValues databaseValues, DbPropertyValues resolvedValues) { }
public void Calling_SetValues_with_dictionary_of_derived_type_works() { var fromProperties = new Dictionary<string, object> { { "Id", 1 } }; var fromValues = new DbPropertyValues(new TestInternalPropertyValues<FakeDerivedTypeWithProps>(fromProperties)); var toProperties = new Dictionary<string, object> { { "Id", 0 } }; var toValues = new DbPropertyValues(new TestInternalPropertyValues<FakeTypeWithProps>(toProperties)); toValues.SetValues(fromValues); Assert.Equal(1, toValues["Id"]); }
public void Attempt_to_copy_values_from_null_object_throws() { var values = new DbPropertyValues(new TestInternalPropertyValues<FakeTypeWithProps>()); Assert.Equal("obj", Assert.Throws<ArgumentNullException>(() => values.SetValues((object)null)).ParamName); }
private static void PrintPropertyValues(DbPropertyValues values) { foreach (var propertyName in values.PropertyNames) { if (propertyName.ToString().Equals("userpwd")) Console.WriteLine(" - {0}: {1}", propertyName, values[propertyName]); } }
public override void OnModify(DbPropertyValues originalValues, DbPropertyValues currentValues) { base.OnModify(originalValues, currentValues); SetBookingRequestLastUpdated(); }
public void Non_Generic_DbPropertyValues_SetValues_with_a_dictionary_works_on_the_underlying_dictionary() { var fromValues = new DbPropertyValues(CreateSimpleValues()); fromValues["Id"] = 1; var toValues = new DbPropertyValues(CreateSimpleValues()); toValues.SetValues(fromValues); Assert.Equal(1, toValues["Id"]); }
//获取要记录的日志内容 private string GetLogContent(DbPropertyValues values, IEnumerable<string> properties) { Dictionary<string, string> result = new Dictionary<string, string>(); foreach (var propertyName in properties) { var value = values[propertyName]; if (value is DbPropertyValues) { var complexPropertyValues = (DbPropertyValues)value; result.Add(propertyName, GetLogContent(complexPropertyValues, complexPropertyValues.PropertyNames)); } else { result.Add(propertyName, (value ?? "").ToString()); } } return result.ToJson(); }
public void SetValues_when_nested_dictionary_is_for_wrong_type_throws() { var fromProperties = new Dictionary<string, object> { { "Id", 1 } }; var fromValues = new DbPropertyValues(new TestInternalPropertyValues<FakeTypeWithProps>(fromProperties)); var toProperties = new Dictionary<string, object> { { "Id", 0 } }; var toValues = new DbPropertyValues(new TestInternalPropertyValues<FakeDerivedTypeWithProps>(toProperties)); Assert.Equal( Strings.DbPropertyValues_AttemptToSetValuesFromWrongType( typeof(FakeTypeWithProps).Name, typeof(FakeDerivedTypeWithProps).Name), Assert.Throws<ArgumentException>(() => toValues.SetValues(fromValues)).Message); }
public void Writing_values_to_non_generic_DbPropertyValues_for_a_whitespace_property_name_throws() { var values = new DbPropertyValues(CreateSimpleValues()); Assert.Equal( Strings.ArgumentIsNullOrWhitespace("propertyName"), Assert.Throws<ArgumentException>(() => values[" "] = 0).Message); }
private static DbPropertyValues ResolverConflitos(DbPropertyValues dbPropertyValues1, DbPropertyValues dbPropertyValues2, DbPropertyValues dbValues) { throw new NotImplementedException(); }
public void Reading_values_from_non_generic_DbPropertyValues_uses_the_internal_dictionary_and_returns_a_non_generic_dictionary() { var properties = new Dictionary<string, object> { { "Id", 1 } }; var values = new DbPropertyValues(new TestInternalPropertyValues<FakeTypeWithProps>(properties)); Assert.Equal(1, values["Id"]); }
private void TestScalarOriginalValue(DbEntityEntry entityEntry, DbPropertyEntry<Building, string> propertyEntry, Type objectType, DbPropertyValues originalValues, string initialValue) { var initialState = entityEntry.State; if (initialState == EntityState.Added) { Assert.Throws<InvalidOperationException>(() => { var _ = propertyEntry.OriginalValue; }).ValidateMessage ("DbPropertyValues_CannotGetValuesForState", "OriginalValues", "Added"); Assert.Throws<InvalidOperationException>(() => propertyEntry.OriginalValue = "").ValidateMessage( "DbPropertyValues_CannotGetValuesForState", "OriginalValues", "Added"); return; } if (initialState == EntityState.Detached) { Assert.Throws<InvalidOperationException>(() => { var _ = propertyEntry.OriginalValue; }).ValidateMessage ("DbPropertyEntry_NotSupportedForDetached", "OriginalValue", propertyEntry.Name, entityEntry.Entity.GetType().Name); Assert.Throws<InvalidOperationException>(() => propertyEntry.OriginalValue = "").ValidateMessage( "DbPropertyEntry_NotSupportedForDetached", "OriginalValue", propertyEntry.Name, entityEntry.Entity.GetType().Name); return; } Assert.Equal(initialState == EntityState.Modified, propertyEntry.IsModified); Assert.Equal(initialValue, propertyEntry.OriginalValue); // Set to same value; prop should not get marked as modified propertyEntry.OriginalValue = initialValue; Assert.Equal(initialState == EntityState.Modified, propertyEntry.IsModified); Assert.Equal(initialState, entityEntry.State); // Set to new value; prop marked as modified propertyEntry.OriginalValue = "New Value"; Assert.Equal("New Value", propertyEntry.OriginalValue); CheckPropertyIsModified(entityEntry, propertyEntry, initialState); // New value reflected in record Assert.Equal("New Value", originalValues[propertyEntry.Name]); // Change record; new value reflected in entry originalValues[propertyEntry.Name] = "Another Value"; Assert.Equal("Another Value", propertyEntry.OriginalValue); // Set to null propertyEntry.OriginalValue = null; Assert.Equal(null, propertyEntry.OriginalValue); }
public void Attempt_to_copy_values_from_null_dictionary_on_non_generic_DbPropertyValues_throws() { var values = new DbPropertyValues(new TestInternalPropertyValues<FakeTypeWithProps>()); Assert.Equal("propertyValues", Assert.Throws<ArgumentNullException>(() => values.SetValues(null)).ParamName); }
private void TestScalarCurrentValue(DbEntityEntry entityEntry, DbPropertyEntry<Building, string> propertyEntry, DbPropertyValues currentValues, Func<string> getter, string initialValue) { var initialState = entityEntry.State; Assert.Equal(initialState == EntityState.Modified, propertyEntry.IsModified); Assert.Equal(initialValue, propertyEntry.CurrentValue); // Set to same value; prop should not get marked as modified propertyEntry.CurrentValue = initialValue; Assert.Equal(initialState == EntityState.Modified, propertyEntry.IsModified); Assert.Equal(initialState, entityEntry.State); // Set to new value; prop marked as modified propertyEntry.CurrentValue = "New Value"; Assert.Equal("New Value", propertyEntry.CurrentValue); Assert.Equal("New Value", getter()); CheckPropertyIsModified(entityEntry, propertyEntry, initialState); // New value reflected in record if (initialState != EntityState.Deleted && initialState != EntityState.Detached) { Assert.Equal("New Value", currentValues[propertyEntry.Name]); // Change record; new value reflected in entry currentValues[propertyEntry.Name] = "Another Value"; Assert.Equal("Another Value", propertyEntry.CurrentValue); Assert.Equal("Another Value", getter()); } // Set to null propertyEntry.CurrentValue = null; Assert.Null(propertyEntry.CurrentValue); Assert.Null(getter()); }
public void Writing_values_to_non_generic_DbPropertyValues_uses_the_internal_dictionary() { var values = new DbPropertyValues( new TestInternalPropertyValues<FakeTypeWithProps>( new Dictionary<string, object> { { "Id", 0 } })); values["Id"] = 1; Assert.Equal(1, values["Id"]); }
public virtual void OnModify(DbPropertyValues originalValues, DbPropertyValues currentValues) { this.DetectStateUpdates(originalValues, currentValues); }
public void Complex_values_cannot_be_set_to_actual_complex_object_instance_in_a_property_dictionary() { var values = new DbPropertyValues(CreateSimpleValues()); Assert.Equal( Strings.DbPropertyValues_AttemptToSetNonValuesOnComplexProperty, Assert.Throws<ArgumentException>(() => values["NestedObject"] = new FakeTypeWithProps()).Message); }
private void ClientChooses(DbPropertyValues current, DbPropertyValues other, DbPropertyValues resolved) { resolved["FirstName"] = other["FirstName"]; resolved["LastName"] = current["LastName"]; }
public void Complex_values_can_be_set_at_the_complex_object_level_into_a_non_generic_dictionary_using_a_non_generic_dictionary() { SettingNestedValuesTest( (values, nestedValues) => new DbPropertyValues(values)["NestedObject"] = new DbPropertyValues(nestedValues)); }
public void OnDelete(DbPropertyValues originalValues) { SetBookingRequestLastUpdated(); }
public void Reading_value_from_non_generic_DbPropertyValues_for_an_empty_property_name_throws() { var values = new DbPropertyValues(CreateSimpleValues()); Assert.Equal( Strings.ArgumentIsNullOrWhitespace("propertyName"), Assert.Throws<ArgumentException>(() => { var _ = values[""]; }).Message); }
public void Calling_SetValues_with_instance_of_derived_type_works() { var properties = new Dictionary<string, object> { { "Id", 0 } }; var values = new DbPropertyValues(new TestInternalPropertyValues<FakeTypeWithProps>(properties)); values.SetValues( new FakeDerivedTypeWithProps { Id = 1 }); Assert.Equal(1, values["Id"]); }
public void Non_Generic_DbPropertyValues_SetValues_works_on_the_underlying_dictionary() { var properties = new Dictionary<string, object> { { "Id", 0 } }; var values = new DbPropertyValues(new TestInternalPropertyValues<FakeTypeWithProps>(properties)); values.SetValues( new FakeTypeWithProps { Id = 1 }); Assert.Equal(1, values["Id"]); }