Below is my code to add new records in db. I am using EF Core.
In my code I am checking first if existing user id data is there or not in db, if there is data then it should update record otherwise it should create.
But my problem is every time it is adding new record instead of updating existing one..any idea on this.
Below is my code :
public async Task<int> Create(UserPreference _object)
{
var userPreferenceDetails = applicationDbContext.UserPreferences.Where(x => x.UserId == _object.UserId).FirstOrDefault();
if(userPreferenceDetails != null)
{
if (_object.Image != null)
{
var webRootPath = hostingEnv.WebRootPath;
var fileName = Path.GetFileName(_object.Image.FileName);
var filePath = Path.Combine(hostingEnv.WebRootPath, "images\\User", fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await _object.Image.CopyToAsync(fileStream);
}
userPreferenceDetails.ImagePath = filePath;
//_object.ImagePath = filePath;
}
userPreferenceDetails.Name = _object.Name;
userPreferenceDetails.Location = _object.Location;
userPreferenceDetails.DateOfBirth = _object.DateOfBirth;
userPreferenceDetails.AboutMe = _object.AboutMe;
userPreferenceDetails.MatchPreference = _object.MatchPreference;
userPreferenceDetails.PlayScore = _object.PlayScore;
userPreferenceDetails.LocationPreference = _object.LocationPreference;
var obj = applicationDbContext.UserPreferences.Update(_object);
return applicationDbContext.SaveChanges();
} else
{
if (_object.Image != null)
{
var webRootPath = hostingEnv.WebRootPath;
var fileName = Path.GetFileName(_object.Image.FileName);
var filePath = Path.Combine(hostingEnv.WebRootPath, "images\\User", fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await _object.Image.CopyToAsync(fileStream);
}
_object.ImagePath = filePath;
}
var obj = await applicationDbContext.UserPreferences.AddAsync(_object);
return applicationDbContext.SaveChanges();
}
}
CodePudding user response:
try this
if(_object.UserId > 0)
{
var userPreferenceDetails = applicationDbContext.UserPreferences.Where(x =>
x.UserId == _object.UserId).FirstOrDefault();
if(userPreferenceDetails == null) return 0;
if (_object.Image != null)
{
....your code
}
userPreferenceDetails.Name = _object.Name;
userPreferenceDetails.Location = _object.Location;
userPreferenceDetails.DateOfBirth = _object.DateOfBirth;
userPreferenceDetails.AboutMe = _object.AboutMe;
userPreferenceDetails.MatchPreference = _object.MatchPreference;
userPreferenceDetails.PlayScore = _object.PlayScore;
userPreferenceDetails.LocationPreference = _object.LocationPreference;
}
else
{
if (_object.Image != null)
{
...your code
}
applicationDbContext.UserPreferences.Add(_object);
}
var result= await applicationDbContext.SaveChangesAsync();
return result;
}
CodePudding user response:
The call to update is not needed . Similar issue : Entity Framework Core: Update() method INSERTs instead of UPDATEs on dependent entity