Base solution for your next web application
Open Closed

An internal error occurred during your request #509


User avatar
0
sampath created
public async Task<int> CreatePropertyAsync(CreateOrEditPropertyInput input)
        {
            var property = input.Property.MapTo<Property>();
            var propertyId = await _propertyRepository.InsertAndGetIdAsync(property);
            return propertyId;
        }
public async Task<int?> EditPropertyAsync(CreateOrEditPropertyInput input)
        {
            var property = await _propertyRepository.FirstOrDefaultAsync(p => p.Id == input.Property.Id);
            input.Property.MapTo(property);
            await _propertyRepository.UpdateAsync(property);
            return input.Property.Id;
        }
public class CreateOrEditPropertyInput : IInputDto
    {
        [Required]
        public PropertyEditDto Property { get; set; }
    }
[AutoMap(typeof(Property))]
    public class PropertyEditDto
    {
        public const int MaxLength = 50;
        public int? Id { get; set; }
        public bool IsVacant { get; set; }
        public bool IsPropertyToConsider { get; set; }

        [Required]
        [MaxLength(MaxLength)]
        public string Dist { get; set; }

        [Required]
        [MaxLength(MaxLength)]
        public string Sec { get; set; }
  }

JS

vm.init = function () {
                propertyService.getPropertyForEdit({
                    id: vm.property.id
                }).success(function (result) {
                    vm.property = result.property;
                                    

                });
            };
public async Task<GetPropertyForEditOutput> GetPropertyForEdit(NullableIdInput<int> input)
        {
            var output = new GetPropertyForEditOutput();

            if (!input.Id.HasValue)//create
            {
                output.Property = new PropertyEditDto();
             }
            else //edit
            {
                var property = await _propertyRepository.FirstOrDefaultAsync(p => p.Id == input.Id.Value);
                output.Property = property.MapTo<PropertyEditDto>();
               
            }

            return output;
        }
public class GetPropertyForEditOutput : IOutputDto
    {
        public PropertyEditDto Property { get; set; }
       
    }

JS

//to save Property
            function createOrEditProperty() {
                vm.saving = true;
                propertyService.createOrEditPropertyAsync({ property: vm.property }).success(function (data) {
                    vm.property.id = data;
                    abp.notify.info(app.localize('SavedSuccessfully'));
                }).finally(function () {
                    vm.saving = false;
                });
            }

Q : Using above code snippets where I can "Create" and "Edit" the property correctly.App's UI is having many tabs and each and every tab is having "Save" button.Hence after creating the property where user can do any change again and can press the "Save" button again.The problem comes on that moment.It gives "An internal error occurred during your request!" error box when executes below line inside the "EditPropertyAsync()" method.This is the line :

input.Property.MapTo(property);

. Could you tell me why this is happening ? This is working fine when I use the "Edit" button.The problem occurs when I try to change the record after Creating it on the same screen without going to the "Edit" button.

Note : After creating the record,it returned the newly created property id back to the ui and by using that id where I decide it to be edited record.Then it executes "EditPropertyAsync()" method.That is the way I did it when user tries to use "Save" button again on the same screen without going to the Edit button. This time only it gives above mentioned error.

Note 2 : I have found out this from log file :

Source value:
0 ---> System.InvalidOperationException: The property 'Id' is part of the object's key information and cannot be modified.

Complete Exception :

ERROR 2015-11-19 10:38:16,338 [16   ] lers.Filters.AbpExceptionFilterAttribute - AutoMapper.AutoMapperMappingException: 

Mapping types:
Int32 -> Int32
System.Int32 -> System.Int32

Destination path:
Property.Address.Address.Id.Id

Source value:
0 ---> System.InvalidOperationException: The property 'Id' is part of the object's key information and cannot be modified. 
   at System.Data.Entity.Core.Objects.EntityEntry.VerifyEntityValueIsEditable(StateManagerTypeMetadata typeMetadata, Int32 ordinal, String memberName)
   at System.Data.Entity.Core.Objects.EntityEntry.GetAndValidateChangeMemberInfo(String entityMemberName, Object complexObject, String complexObjectMemberName, StateManagerTypeMetadata& typeMetadata, String& changingMemberName, Object& changingObject)
   at System.Data.Entity.Core.Objects.EntityEntry.EntityMemberChanging(String entityMemberName, Object complexObject, String complexObjectMemberName)
   at System.Data.Entity.Core.Objects.EntityEntry.EntityMemberChanging(String entityMemberName)
   at System.Data.Entity.Core.Objects.ObjectStateEntry.System.Data.Entity.Core.Objects.DataClasses.IEntityChangeTracker.EntityMemberChanging(String entityMemberName)
   at System.Data.Entity.DynamicProxies.Address_DC03C9817912E18A8FAA931110EEEF10FBB1519A7553CF5CAA7822ECD0C0FCBF.EntityMemberChanging(String )
   at System.Data.Entity.DynamicProxies.Address_DC03C9817912E18A8FAA931110EEEF10FBB1519A7553CF5CAA7822ECD0C0FCBF.set_Id(Int32 )
   at lambda_method(Closure , Object , Object )
   at AutoMapper.Internal.PropertyAccessor.SetValue(Object destination, Object value)
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.AssignValue(PropertyMap propertyMap, Object mappedObject, Object propertyValueToAssign)
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
   --- End of inner exception stack trace ---
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
   at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
   at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
   at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
   at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
   at AutoMapper.MappingEngine.MapCore(Object source, Object destination, Type sourceType, Type destinationType, MappingOperationOptions options)
   at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source, TDestination destination, Action`1 opts)
   at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source, TDestination destination)
   at AutoMapper.Mapper.Map[TSource,TDestination](TSource source, TDestination destination)
   at Abp.AutoMapper.AutoMapExtensions.MapTo[TSource,TDestination](TSource source, TDestination destination)
   at Joshi.IP.IpProperties.PropertyAppService.&lt;EditPropertyAsync&gt;d__11.MoveNext() in d:\Freelance Work\Nipun-SPA\SPA\island\Joshi.IP.Application\IpProperties\PropertyAppService.cs:line 77
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Joshi.IP.IpProperties.PropertyAppService.<CreateOrEditPropertyAsync>d__5.MoveNext() in d:\Freelance Work\Nipun-SPA\SPA\island\Joshi.IP.Application\IpProperties\PropertyAppService.cs:line 52
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Abp.Threading.InternalAsyncHelper.&lt;AwaitTaskWithPostActionAndFinallyAndGetResult&gt;d__10`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Abp.Threading.InternalAsyncHelper.&lt;AwaitTaskWithFinallyAndGetResult&gt;d__c`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Threading.Tasks.TaskHelpersExtensions.&lt;CastToObject&gt;d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Abp.Extensions.ExceptionExtensions.ReThrow(Exception exception)
   at Abp.WebApi.Controllers.Dynamic.Selectors.DynamicHttpActionDescriptor.<ExecuteAsync>b__0(Task`1 task)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Web.Http.Controllers.ApiControllerActionInvoker.&lt;InvokeActionAsyncCore&gt;d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Web.Http.Controllers.AuthenticationFilterResult.&lt;ExecuteAsync&gt;d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()

5 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Hi,

    Actually, exception is clear: You are trying to set Id to a different value on update method. But I don't know how this happen. I implemented same pattern in the application before and it's working. Can you check what is the Id coming to the EditPropertyAsync method? Check if input.Property.Id is same as property.Id As a solution, you can define a custom mapping from PropertyEditDto to Property which excludes the Id property. But this should not be needed normally. BTW, it's not needed to this code: await _propertyRepository.UpdateAsync(property); since entities are automatically saved in a UOW (<a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work#DocAutoSaveChanges">http://www.aspnetboilerplate.com/Pages/ ... aveChanges</a>)

  • User Avatar
    0
    sampath created

    Hi Halil,

    Thanks for the reply. Actually the ids are the same. Please see the attached image. One thing I have to note that here that is, The relationship between the "Properties" and "Addresses" tables are 1 : 1 (I have mentioned it on the image also).Is that the issue here ? If so then how can I sort out this issue ?

    If there is no other solution could you tell me how to do custom mapping as you mentioned above.Just a reference or simple example is more than enough. Thanks in advance.

    Here is the imge url : <a class="postlink" href="http://imgur.com/a/cJdei">http://imgur.com/a/cJdei</a>

    Address :

    [Table("IpAddresses")]
        public class Address : FullAuditedEntity
        {
            public const int MaxLength = 50;
    
            [Key, ForeignKey("Property")]
            public override int Id { get; set; }
    
            [Required]
            [MaxLength(MaxLength)]
            public virtual string StreetNumber { get; set; }
    
            [Required]
            [MaxLength(MaxLength)]
            public virtual string StreetName { get; set; }
    
            [ForeignKey("CityId")]
            public virtual City City { get; set; }
            public virtual int CityId { get; set; }
    
            [ForeignKey("StateId")]
            public virtual State State { get; set; }
            public virtual int StateId { get; set; }
    
            public virtual Property Property { get; set; }
        }
    
  • User Avatar
    0
    hikalkan created
    Support Team

    Hi,

    You can check this example:

    <a class="postlink" href="https://github.com/aspnetzero/aspnet-zero/blob/master/src/MyCompanyName.AbpZeroTemplate.Application/CustomDtoMapper.cs#L29">https://github.com/aspnetzero/aspnet-ze ... per.cs#L29</a>

    Add your custom mappings to CustomDtoMapper class as in this example. In this code, I mapped User to UserDto but ignored Password property for security. Your will be something like that:

    Mapper.CreateMap<Property, PropertyEditDto>()
        .ReverseMap()
        .ForMember(property => property.Id, options => options.Ignore());
    

    Don't forget to remove [AutoMap(typeof(Property))] attribute from PropertyEditDto class.

  • User Avatar
    0
    sampath created

    Hi Halil,

    That url is not working ? Could you correct it ? Thank in advance.

  • User Avatar
    0
    sampath created

    Hi Halil,

    Thank you so much :)

    The problem was on the "AddressDto" mapping.I have done as you said and now it's working.Thanks again :)

    Mapper.CreateMap<Address, AddressDto>()
                  .ReverseMap()
                  .ForMember(address => address.Id, options => options.Ignore());