Entity Framework 6 - update fails (disconnected scenario) - c#

I'm trying to update an instance with Entity Framework 6. I suppose it's a disconnected scenario. And the update fails - no errors but the properties I change do not save in DB.
Method in controller
var managers = _iManagerRepository.Managers.ToList();
var manager = managers.FirstOrDefault(m => m.Id == currentUserId);
if (manager != null)
{
manager.ContactDetail.FirstName = withTokenDto.managerInfoModel.FirstName;
manager.ContactDetail.SecondName = withTokenDto.managerInfoModel.SecondName;
manager.ContactDetail.LastName = withTokenDto.managerInfoModel.LastName;
_iManagerRepository.UpdateManager(manager);
return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK));
}
Method in repository:
public void UpdateManager(Manager manager)
{
using (LightCRMEntities context = new LightCRMEntities())
{
context.Managers.Attach(manager);
context.Entry<Manager>(manager).State = EntityState.Modified;
context.SaveChanges();
}
}

Related

Getting an error when trying to update users details with EF Core

Using .NET6 and EF Core I'm trying to update a user's details in the database and receiving an error:
DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s), but actually affected 0 row(s);
I'm using a class called AppUser which inherits from IdentityUser.
My update method looks like this:
public async Task<IActionResult> UpdateAccountAsync(AppUser user)
{
if (!ModelState.IsValid) return View(nameof(MyAccount), user);
user.ModifiedDateT = DateTime.UtcNow;
await _userRepository.UpdateAsync(user);
return View(nameof(MyAccount), user);
}
With the UpdateAsync method like:
public async Task<AppUser> UpdateAsync(AppUser entity)
{
if (entity == null)
throw new InvalidOperationException("Cannot update a null object!");
entity.ModifiedDateT = DateTime.UtcNow;
var dbEntity = _context.Update(entity);
await _context.SaveChangesAsync();
return dbEntity.Entity;
}
Using this interface:
Task<AppUser> UpdateAsync(AppUser entity);
With my limited understanding of EF Core, do you have to bring in the AppUser, make changes to the AppUser, then update and save? It's not working out for me
I figured it out in the end with:
public async Task<AppUser > UpdateAsync(AppUser entity)
{
if (entity == null) throw new InvalidOperationException("Cannot update a null object!");
entity.ModifiedDateT = DateTime.UtcNow;
var dbUser = _context.Users
.FirstOrDefault(s => s.Id.Equals(entity.Id));
if (dbUser != null)
{
dbUser.FirstName = entity.FirstName;
dbUser.LastName = entity.LastName;
dbUser.Email = entity.Email;
dbUser.ModifiedDateT = DateTime.UtcNow;
}
await _context.SaveChangesAsync();
return entity;
}
I didn't realize that the property being passed in won't update, but I needed to get a new property from the DB and then apply the changes to that property and SaveChangesAsync().

What can be the equivalent of entity in .NET Core 3.1?

The core works perfectly in ASP.NET MVC but I have problems in ASP.NET Core near "Entities" - please help
public ActionResult AddOrEdit(int id = 0)
{
SELECTEDEMPLOYEE emp = new SELECTEDEMPLOYEE();
using (Entities db = new Entities())
{
if (id != 0)
{
emp = db.SELECTEDEMPLOYEEs.Where(x => x.ID == id).FirstOrDefault();
emp.SelectedIDArray = emp.SELECTEDEMPLOYEEIDS.Split(',').ToArray();
}
emp.EmployeeCollection = db.VIEW_USER.ToList();
}
return View(emp);
}
Maybe in your second project you do not have Entity class (context class).

Entity Framework one-to-many relation, updating the one side

I have a set of endpoints which may or may not belong to an organization and an organization can have many or zeros endpoints in it. I want to remove a specific endpoint from an organization. I have written this method but I can't figure out why it is not working:
public void DeleteEndpointFromOrganization(Guid id, int organiationId)
{
using (var db = new Context())
{
var organization = GetOrganizationById(organiationId);
var endpointSystem = organization.EndpointSystems.FirstOrDefault(e => e.Id == id);
if (endpointSystem != null)
{
organization.EndpointSystems.Remove(endpointSystem);
}
db.Organizations.AddOrUpdate(organization);
db.SaveChanges();
}
}

How query by global secondary index with DynamoDBContext

i have this class with this attributes:
ContactId -> HashKey
Email -> Global Seconday Index Hash Key
CreatedAt -> Property
Actually, i have this method, but throw me an exception because "Email" property is not a HashKey. How can i get an item using a secondary index and DynamoDBContext class? I found some examples, but all of them uses a low-level api.
public Contact Get(string email)
{
Contact entity = null;
using (var context = new DynamoDBContext(new AmazonDynamoDBClient()))
{
entity = context.Load(new Contact() { Email = email });
}
return entity;
}
EDIT: Actually, this code work for me. It assume that "email" is unique:
public Contact Get(string email)
{
Contact entity = null;
using (var context = new DynamoDBContext(new AmazonDynamoDBClient()))
{
entity = context.Query<Contact>(email, new DynamoDBOperationConfig {IndexName = "Email-index"}).FirstOrDefault();
}
return entity;
}
If using .NET core or .NET 5 and higher with async API calls, the following should work. Note the QueryAsync method and GetRemainingAsync().Result which returns the result of the completed query task.
public Contact Get(string email)
{
Contact entity = null;
using (var context = new DynamoDBContext(new AmazonDynamoDBClient()))
{
entity = context.QueryAsync<Contact>(email,
new DynamoDBOperationConfig {IndexName = "Email-index"})
.GetRemainingAsync().Result.FirstOrDefault();
}
return entity;
}

How to update an entity using Entity Framework from Business Layer?

I my web application structured with 3 layers, controller, business logic and repository.
From the BL layer I am updating an entity with the following code. As you can see I am updating property by property.
I would like to know if there is a better way to do it, removing this manual mapping.
---------------------- CONTROLLER
public IHttpActionResult Put(int id, DeviceDTO dto)
{
GaDevice device = Mapper.Map<GaDevice>(dto);
deviceBLL.Update(id, device);
return Ok();
}
---------------------- BL
public void Update(int id, GaDevice entity)
{
bool hasValidId = GetById(id) != null ? true : false;
if (hasValidId == true)
{
GaDevice device = deviceRepo.GetById(id);
device.CanNotifyPc = entity.CanNotifyPc; // NOT SURE HERE
device.CanNotifyPrinter = entity.CanNotifyPrinter;
device.LocationId = entity.LocationId;
device.Name = entity.Name;
device.Note = entity.Note;
device.OperativeFromTime = entity.OperativeFromTime;
device.OperativeToTime = entity.OperativeToTime;
deviceRepo.Update(device );
deviceRepo.Save();
}
---------------- Repository
public void Update(GaDevice entity)
{
context.Entry(entity).State = EntityState.Modified;
}
What about saving the changes made to the context in the Update()?
Otherwise, what does your code in the Save() do?
public void Update(GaDevice entity)
{
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
}

Categories