Hi there, I have an simple entity like that
public class AnnouncementEntity { public int Id { get; set;} public string Header {get; set;} public string Content {get; set;} }
In my application service i have an update method: public async Task UpdateAnnouncement(EditAnnouncementInputDto input) {
AnnouncementEntity announce = new AnnouncementEntity()
{
Id = input.Id,
Header = input.Header
};
await _announceRepository.UpdateAsync(announce);
}
this method updates the entity but i have a Content column and this update makes Content NULL.
How can i update columns that i want not all columns?
10 Answer(s)
-
0
To do that, you should attach the entity.
// Create new stub with correct id and attach to context. var announce = new AnnouncementEntity { Id = input.Id }; repository.As<EfCoreRepositoryBase<MyDbContext, AnnouncementEntity>>().Table.Attach(announce); // Now the entity is being tracked by EF, update required properties. announce.Header = input.Header; // EF knows only to update the properties specified above. _unitOfWorkManager.Current.SaveChanges();
-
0
Thank you for your reply.
I understand that i should attach the entity to the DbContext.
But i cant figure it out how.
Could you be more specific with this line:
repository.As<EfCoreRepositoryBase<MyDbContext, AnnouncementEntity>>().Table.Attach(announce);
Btw im not using EfCore.
my _announcementRepo doesnt have "As" method.
-
0
Could you be more specific with this line:
repository.As<EfCoreRepositoryBase<MyDbContext, AnnouncementEntity>>().Table.Attach(announce);
Btw im not using EfCore.
Please specify that in future questions.
And simply remove Core.
my _announcementRepo doesnt have "As" method.
Add this using directive:
using Abp.Extensions;
You can hold Ctrl + . to fix such reference issues.
-
0
Thank you for your reply and patience (:
I solved reference and using problems. But when code comes to this line
repository.As<EfCoreRepositoryBase<MyDbContext, AnnouncementEntity>>().Table.Attach(announce);
Unable to cast object of type 'Castle.Proxies.IRepository
1Proxy_4' to type 'Abp.EntityFramework.Repositories.EfRepositoryBase
2[ProjectName.EntityFramework.MyDbContext,AnnouncementEntity]' -
0
Is your DbContext actually called MyDbContext?
-
0
Ofc not :)
-
0
This is the part of my Update service method.
public async Task UpdateAnnouncement(EditAnnouncementInputDto input) { var announce = input.MapTo<AnnounceEntity>();
_announceRepository.As<EfRepositoryBase<MyProjectDbContext, AnnouncementEntity>>().Table.Attach(announce); await _duyuruRepository.UpdateAsync(announce); }
-
0
Can you put a breakpoint and check the actual type of _announceRepository?
-
0
Its type is "IRepository<AnnounceEntity>"
-
0
Try this:
ProxyHelper.UnProxy(_announceRepository).As<EfRepositoryBase<MyProjectDbContext, AnnouncementEntity>>().Table.Attach(announce);
Add this using directive:
using Abp.Reflection;