question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Issue when calling IRepository<>.Update()

See original GitHub issue

Hi,

Using ABP 0.7.7, Entity Framework 6.1.3,

I am getting the following exception when I am updating a record that already exists in the destination table:

image

My table is defined as follows:

CREATE TABLE [Platform].[ChangeLog](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Date] [Date] NOT NULL,
    [DeveloperInitials] [nvarchar](3) NOT NULL,
    [Entry] [nvarchar](max) NOT NULL,
    [FogBugReference] [int] NOT NULL,
    [Guid] [nvarchar](36) NOT NULL,
    [IntendedAudience] [int] NOT NULL,
    [Version] [nvarchar](15) NOT NULL,
    [WebsitePropertyId] [smallint] NOT NULL,
 CONSTRAINT [PK_ChangeLog] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [Platform].[ChangeLog]  WITH CHECK ADD  CONSTRAINT [FK_ChangeLog_WebsitePropertys] FOREIGN KEY([WebsitePropertyId])
REFERENCES [Reference].[WebsitePropertys] ([WebsitePropertyID])
GO

ALTER TABLE [Platform].[ChangeLog] CHECK CONSTRAINT [FK_ChangeLog_WebsitePropertys]
GO

and has the following records in it at time of calling the method:

image

As you can see the Id value is 6 that I am supplying to the call to the repository method _PlatformChangeLogRepository.Update(). So what I am trying to work out is why I am getting the exception here. Is it how I am calling ABP or something else?

Below are the relevant class declarations for the various classes referenced above.

   //ABP Repository class
   public interface IOzCpPlatformChangeLogRepository : IRepository<Platform_ChangeLogModel>
    {
    }

    //EF model class
    public class Platform_ChangeLogModel : OzEfEntity, IEntity
    {
        public int Id { get; set; } // Id (Primary key)
        public DateTime Date { get; set; } // Date
        public string DeveloperInitials { get; set; } // DeveloperInitials
        public string Entry { get; set; } // Entry
        public int FogBugReference { get; set; } // FogBugReference
        public string Guid { get; set; } // Guid
        public int IntendedAudience { get; set; } // IntendedAudience
        public string Version { get; set; } // Version
        public short WebsitePropertyId { get; set; } // WebsitePropertyId

        // Foreign keys
        //**public virtual Reference_WebsitePropertysModel Reference_WebsitePropertysModel { get; set; } // FK_ChangeLogs_WebsitePropertys

        /// <summary>
        ///     Checks if this entity is transient (not persisted to database and it has not an
        ///     <see cref="P:Abp.Domain.Entities.IEntity`1.Id" />).
        /// </summary>
        /// <returns>
        ///     True, if this entity is transient
        /// </returns>
        public bool IsTransient()
       {
            return false;
        }

    }

   //EF configuration class
       public class Platform_ChangeLogConfiguration : EntityTypeConfiguration<Platform_ChangeLogModel>
    {
        public Platform_ChangeLogConfiguration(string schema = "Platform")
        {
            ToTable(schema + ".ChangeLog");
            HasKey(x => x.Id);

            Property(x => x.Id).HasColumnName("Id").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(x => x.Date).HasColumnName("Date").IsRequired();
            Property(x => x.DeveloperInitials).HasColumnName("DeveloperInitials").IsRequired().HasMaxLength(3);
            Property(x => x.Entry).HasColumnName("Entry").IsRequired();
            Property(x => x.FogBugReference).HasColumnName("FogBugReference").IsRequired();
            Property(x => x.IntendedAudience).HasColumnName("IntendedAudience").IsRequired();
            Property(x => x.Guid).HasColumnName("Guid").IsRequired().HasMaxLength(36);
            Property(x => x.Version).HasColumnName("Version").IsRequired().HasMaxLength(15);
            Property(x => x.WebsitePropertyId).HasColumnName("WebsitePropertyId").IsRequired();

            // Foreign keys
            //***HasRequired(a => a.Reference_WebsitePropertysModel).WithMany(b => b Platform_ChangeLogModel).HasForeignKey(c => c.WebsitePropertyId); // FK_ChangeLogs_WebsitePropertys
        }

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:19 (12 by maintainers)

github_iconTop GitHub Comments

1reaction
hikalkancommented, Feb 12, 2016

Also, as I see you did not set Date property which is NOT NULL in the database.

0reactions
saYRamcommented, Nov 15, 2016

Ok. I found the problem. It’s about my codes. But why error throwed i could not understood.

I used this codes to get images of Listing.

            var listingOutput = _service.GetUserListingById(new GetListingInput
            {
                Id = viewModel.Id
            });

This code pieces runs these codes in service layer

    public GetListingOutput GetUserListingById(GetListingInput input)
    {
        GetListingOutput output;
        Listing listing;

        using (CurrentUnitOfWork.DisableFilter("ListingIsActive"))
        {
            using (CurrentUnitOfWork.DisableFilter("ListingPublished"))
            {
                listing = _repository.GetAll().Where(x => x.Id == input.Id && x.CreatorUserId == AbpSession.UserId.Value).FirstOrDefault();
            }
        }

        output = new GetListingOutput();

        if (listing != null)
        {
            output.Exist = true;
            output.Listing = listing.MapTo<ListingDto>();
        }
        else
        {
            output.Exist = false;
            output.Message = AbpSession.UserId.Value + " Bu araç size ait görünmüyor";
            output.Listing = listing.MapTo<ListingDto>();
        }

        return output;
    }

ListingDto is here.

[AutoMap(typeof(Listing))]
public class ListingDto
{
    public long Id { get; set; }

    [Required]
    [StringLength(Listing.MaxTitleLength)]
    public string Title { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    public string Brand { get; set; }
    [Required]
    public string Model { get; set; }

    public bool HomeDelivery { get; set; }

    [Required]
    public double Price { get; set; }

    public PriceTypes PricePeriod { get; set; }

    public FuelTypes FuelType { get; set; }

    public CarTypes CarType { get; set; }

    public TransmissionTypes TransmissionType { get; set; }

    public int Year { get; set; }

    public string Images { get; set; }

    [Required]
    [StringLength(Entities.City.MaxNameLength)]
    public string City { get; set; }

    [Required]
    [StringLength(Entities.County.MaxNameLength)]
    public string County { get; set; }

    [Required]
    [StringLength(Entities.District.MaxNameLength)]
    public string District { get; set; }

    [Required]
    public double Latitude { get; set; }

    [Required]
    public double Longitude { get; set; }

    [Required]
    [StringLength(Listing.MaxLocationLength)]
    public string Location { get; set; }

    public bool IsActive { get; set; }
    public bool Published { get; set; }
}

So, i created a new Service method.

    public GetUserListingImagesOutput GetUserListingImagesById(GetListingInput input)
    {
        GetUserListingImagesOutput output = new GetUserListingImagesOutput();
        //var listing;

        using (CurrentUnitOfWork.DisableFilter("ListingIsActive"))
        {
            using (CurrentUnitOfWork.DisableFilter("ListingPublished"))
            {
                output = _repository.GetAll().Where(x => x.Id == input.Id && x.CreatorUserId == AbpSession.UserId.Value).Select(x => new GetUserListingImagesOutput
                {
                    Images = x.Images
                }).FirstOrDefault();

            }
        }

        return output;
    }



public class GetUserListingImagesOutput
{
    public string Images { get; set; }
}

With this changes the Update medthod above runs well now.

And the Action Medthod here you may want to investigate.

[HttpPost]
[ValidateAntiForgeryToken]
[AbpAuthorize]
public async Task<ActionResult> Edit(UpdateListingViewModel viewModel, IEnumerable<HttpPostedFileBase> files)
{
    if (ModelState.IsValid)
    {
        await AddOrUpdateLocation(viewModel);

        viewModel.Published = IsListingPublished(viewModel.Button);

        UpdateListingInput input = new UpdateListingInput();

        //var listingOutput = _service.GetUserListingById(new GetListingInput
        //{
        //    Id = viewModel.Id
        //});

        var listingImagesOutput = _service.GetUserListingImagesById(new GetListingInput
        {
                Id = viewModel.Id
        });

        if (files != null && files.Count() > 0)
        {

            //Herşeyden önce dizindeki resim dosyalarını sil
            string[] filesToDelete = listingImagesOutput.Images.Split(',');

            foreach (var item in filesToDelete)
            {
                var path = Path.Combine(Server.MapPath("~/images/listing"), item);

                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
            }

            foreach (HttpPostedFileBase file in files)
            {
                if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string guid = Guid.NewGuid().ToString();
                    input.Images += viewModel.Title.ToSlug() + "-" + guid + ".jpg,";

                    //Format is automatically detected though can be changed.
                    ISupportedImageFormat format = new JpegFormat { Quality = 60 };
                    Size size = new Size(825, 0);

                    //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
                    //Initialize the ImageFactory using the overload to preserve EXIF metadata.
                    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                    {
                        var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", viewModel.Title.ToSlug() + "-" + guid, "jpg"));

                        //Load, resize, set the format and quality and save an image.
                        imageFactory.Load(file.InputStream)
                                    .Resize(size)
                                    .Format(format)
                                    .Watermark(new TextLayer()
                                    {
                                        DropShadow = true,
                                        FontFamily = FontFamily.GenericSansSerif,
                                        Text = "KiralaBiOto.com",
                                        Style = FontStyle.Bold,
                                        FontColor = Color.DarkBlue
                                    })
                                    .Save(path);
                    }
                }
            }

            if (input.Images != null)
            {
                input.Images = input.Images.Substring(0, input.Images.Length - 1);
            }
        }

        input.Listing = viewModel.MapTo<ListingDto>();

        var listingUpdateOutput = await _service.UpdateAsync(input);

        if (!listingUpdateOutput.Success)
        {
            this.AddNotification(listingUpdateOutput.Message, NotificationType.Error);
            PostBackCreateForm(viewModel);
            return View(viewModel);
        }

        this.AddNotification("işlem başarı ile gerçekleşti. Onay gerekebilir.", NotificationType.Success);

        return RedirectToAction("Edit", new { id = listingUpdateOutput.Listing.Id });


    }
    return View(PostBackCreateForm(viewModel));
}

Not: In the GetUserListingById medthod i mapped Listing to ListingDto even listing returns null by mistakely.

        if (listing != null)
        {
            output.Exist = true;
            output.Listing = listing.MapTo<ListingDto>();
        }
        else
        {
            output.Exist = false;
            output.Message = AbpSession.UserId.Value + " Bu araç size ait görünmüyor";
            output.Listing = listing.MapTo<ListingDto>();
        }

i removed the line output.Listing = listing.MapTo<ListingDto>(); in else block and tried to run codes before changes to understand if this line causes error. No, same error occured.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Jpa Repository save() doesn't update existing data
I am trying to update data and as I know save() method saves entity if the id is null or update an existing...
Read more >
repository.save() does not update the returned entity when ...
Unfortunately, when I call repository.save() to update an existing entity the object returned does not have the createdBy and createdDate ...
Read more >
Partial Data Update With Spring Data
In this tutorial, we will cover techniques and approaches to performing a partial instead of a full update. 2. Problem. As stated before,...
Read more >
The best Spring Data JpaRepository
In this article, I'm going to show you the best way to use the Spring Data JpaRepository, which, most often, is used the...
Read more >
How to update an entity using Spring Data JPA
Spring Data JPA provides save() method to update the entity. ... Calling repository method to update entity using @Modifying.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found