EF 添加新记录而不是更新记录
Posted
技术标签:
【中文标题】EF 添加新记录而不是更新记录【英文标题】:EF adding new record instead of updating record 【发布时间】:2022-01-06 07:25:34 【问题描述】:下面是我在数据库中添加新记录的代码。我正在使用 EF Core。
在我的代码中,我首先检查数据库中是否存在现有的用户 ID 数据,如果有数据则应更新记录,否则应创建。
但我的问题是每次添加新记录而不是更新现有记录时..对此有任何想法。
下面是我的代码:
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();
【问题讨论】:
【参考方案1】:试试这个
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;
【讨论】:
以上是关于EF 添加新记录而不是更新记录的主要内容,如果未能解决你的问题,请参考以下文章