我是新來的實體框架和LINQ。我被困在一個問題,我需要首先檢查記錄是否已經存在,如果存在,那麼我需要相應地更新列RESUMEID的記錄。如果沒有,那麼我需要添加記錄。我能夠成功添加,但我不知道如何更新LINQ中的記錄。如何在我的ASP.NET MVC 5項目中使用LINQ LAMBDA更新記錄
下面是我的嘗試:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ReferralViewModel viewModel)
{
var candidateId = User.Identity.GetUserId();
// I AM CONFUSED ABOUT BELOW STATEMENT
var IsDupeReferral = _context.Referrals
.Where(r => (r.CandidateId == candidateId)
&& (r.CompanyId == viewModel.CompanyId) && (r.SkillId == viewModel.SkillId))
.Select(r=>r.ReferralId).SingleOrDefault();
if(IsDupeReferral!=0)
{
//IF I FIND DUPE REFERRAL RECORD I WANT TO UPDATE SOME OF THE VALUES IN THAT
_context.Referrals.Where(r => r.ReferralId == IsDupeReferral).
AND UPDATE r.resumeId with viewModel.ResumeId // How to do this?
// NOT SURE ABOUT BELOW LINE EITHER
_context.SaveChanges();
}
else
{
// BELOW CODE IS WORKING FINE
var referral = new Referral
{
ReferralName = viewModel.ReferralName,
ResumeId = viewModel.ResumeId,
CandidateId = candidateId,
DegreeId = viewModel.DegreeId,
CoverLetterId = viewModel.CoverLetterId,
SkillId = viewModel.SkillId
};
if (!string.IsNullOrEmpty(viewModel.TempCompany))
{
var newCompany = new Company
{
CompanyName = viewModel.TempCompany
};
newCompany.Referrals.Add(referral);
_context.Companies.Add(newCompany); ;
}
else
{
referral.CompanyId = viewModel.CompanyId.Value;
_context.Referrals.Add(referral);
}
_context.SaveChanges();
}
return RedirectToAction("ReferralCenter");
}
先生,這是必要的嗎? '_context.Entry(referral).State = System.Data.EntityState.Modified;' – Unbreakable
以下答案用途。 FirstOrDefault。你能否告訴我應該使用哪一個。 FirstOrDefault還是SingleOrDefault? – Unbreakable
EF是不是足夠聰明,知道我正在修改一行?或者我們需要明確設置行狀態? – Unbreakable