I am basically trying to handle unique constraint validation in my .Net API. I have two unique key cosntraints on two fields in my table.
If you see my code below , I am trying to check if the record exists. I am looking at returning a boolean value if the record exist. is that possible. For the time being, I am returning null.
Is this the best way to do it.
[HttpPost]
[SkipTokenAuthorization]
[Route("api/classificationoverrides/create")]
public IHttpActionResult Create(ClassificationItemViewModelCreate model)
{
var mgrClassificationService = GetService<MGR_STRT_CLASSIFICATION>();
var isExists = mgrClassificationService.Where(x =>
x.MANAGERSTRATEGYID == model.ManagerStrategyId && x.PRODUCT_ID == model.ProductId).FirstOrDefault();
if (isExists == null)
{
var mgrClassficationOverride = new MGR_STRT_CLASSIFICATION();
if (model != null)
{
mgrClassficationOverride.PRODUCT_ID = model.ProductId;
mgrClassficationOverride.LEGACY_STRATEGY_ID = model.LegacyStrategyId;
mgrClassficationOverride.STRATEGY_ID = model.StrategyId;
mgrClassficationOverride.MANAGERSTRATEGY_TYPE_ID = model.ManagerStrategyTypeId;
mgrClassficationOverride.MANAGERSTRATEGYID = model.ManagerStrategyId;
mgrClassficationOverride = mgrClassificationService.Create(mgrClassficationOverride);
}
return Ok(mgrClassficationOverride);
}
else
{
return null;
}
}
Related
I have very weird problem
My code it works fine if I login and use then it save the preferences etc.
But problem starts when I login, do some selections, and logout and login as another user, then upon saving it also remembers the seelctions I had done wfor the other user, the last one and save that also.
How to prevent this?
private ApplicationDbContext db = new ApplicationDbContext();
...
public IHttpActionResult Add(UserPreferencesDto model)
{
model.UserId = User.Identity.GetUserId();
var userPreferences = db.UserPreferences.Where(u =>
u.UserId == model.UserId &&
u.Key == model.Key.Trim())
.FirstOrDefault();
List<int> StatesCollection = new List<int>();
var param = model.Value.Trim();
string[] paramSplitted = param.Split(',');
if (userPreferences != null)
{
if (string.IsNullOrEmpty(userPreferences.Value) == false)
{
var trimmedPreferenceValue = userPreferences.Value.Trim('[', ']');
if (string.IsNullOrEmpty(trimmedPreferenceValue) == false)
{
StatesCollection = trimmedPreferenceValue.Split(',')
.Select(s => Convert.ToInt32(s)).ToList<int>();
}
if (model.IsStateSelected == false && paramSplitted.Count() == 1
&& StatesCollection.Contains(int.Parse(param.Trim())))
{
StatesCollection = StatesCollection.Where(sa => sa != int.Parse(param)).ToList<int>();
userPreferences.Value = StatesCollection.Count > 0 ? JsonConvert.SerializeObject(StatesCollection) : "";
}
else if (model.IsStateSelected && paramSplitted.Count() == 1
&& !StatesCollection.Contains(int.Parse(param)))
{
StatesCollection.Add(int.Parse(param));
userPreferences.Value = JsonConvert.SerializeObject(StatesCollection);
}
}
else
{
StatesCollection.Add(int.Parse(param));
userPreferences.Value = JsonConvert.SerializeObject(StatesCollection);
}
}
else
{
if (model.IsStateSelected == true)
{
//string[] splittedStates = model.Value.Split(',');
int[] secRolesIds = Array.ConvertAll(paramSplitted, int.Parse);
model.Value = JsonConvert.SerializeObject(secRolesIds);
db.UserPreferences.Add(Mapper.Map<UserPreferences>(model));
}
}
db.SaveChanges();
return Ok();
}
Even if the preferences exist it goes to the last else.
SaveChanges() in entity framework saves ALL tracked changes.
You would have to explicitly discard changes or use untracked entities, only adding them when you wish to save.
https://learn.microsoft.com/en-us/ef/core/querying/tracking
I think you should make the userPreferences variable null before giving a value to it, this way you could prevent it to have a value from the last execution because you would ensure it became null because you forced it to be. By doing so if there is no result in the database when you try to assign a value to it it will remain null for sure and so it will enter to the if with the if (userPreferences != null) and don't go to the else.
I have this action method that checks if an item exists, and if it does, it's to be removed. If it doesn't exist, it's to be added. It's like an on-off-switch for that particular item:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> FrontPageProduct(ViewModelFrontPageProduct frontPageProduct)
{
var fpp = new FrontPageProduct()
{
ProductCategoryId = frontPageProduct.ProductCategoryId,
ProductId = frontPageProduct.ProductId,
SortOrder = 0
};
bool exists = _context.FrontPageProducts
.Any(x => x.ProductCategoryId == frontPageProduct.ProductCategoryId
&& x.ProductId == frontPageProduct.ProductId);
if (exists)
{
var delete = (from d in _context.FrontPageProducts
where (d.ProductCategoryId == frontPageProduct.ProductCategoryId &&
d.ProductId == frontPageProduct.ProductId)
select d).FirstOrDefault();
_context.Remove(delete);
}
else
{
_context.Add(fpp);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index), new { id = fpp.ProductCategoryId, tab = 2 });
}
Now, I feel this is a bit long winded. Is there a shorter, but still readable way of doing this?
You do not have to use Any to determine whether it exists. Basically load it using FirstOrDefault (I used async as I see you use async in save, you can also use it in FirstOrDefault). If it is found you have an instance and you can delete it without additional load:
var fpp = new FrontPageProduct()
{
ProductCategoryId = frontPageProduct.ProductCategoryId,
ProductId = frontPageProduct.ProductId,
SortOrder = 0
};
var fppDB = await _context.FrontPageProducts
.FirstOrDefaultAsync(x => x.ProductCategoryId == frontPageProduct.ProductCategoryId && x.ProductId == frontPageProduct.ProductId);
if (fppDB != null)
{
_context.Remove(fppDB);
}
else
{
_context.Add(fpp);
}
await _context.SaveChangesAsync();
Otherwise you can also use SQL stored procedure and call this one from EF. It will be more efficient.
I need your help please,
I do not know where to start, but I'm doing a recruitment management application with the asp.net mvc and wcf technologies, I have a management part of the offers, to start I have a many-to-many relationship between Offers and Candidates table.
Now I want that when the candidate chooses the offer that suits him, when he clicks on the apply button, the offer's id and the id of the candidate is registered in the CandidateOffre association table.
That's what I did, thank you for telling me what I miss so that the insert is done correctly,
Server side (wcf)
public CandidatDTO CreateCandidat(CandidatDTO c)
{
CandidatEmploi candidatEmp = new CandidatEmploi();
CSRMappers.MapCandidatDTOToEntity(c, candidatEmp);
if (c.OffreEmploi != null && c.OffreEmploi.Any())
{
foreach (var f in c.OffreEmploi)
{
if (f.IDOffre == 0)
{
OffreEmploi of = new OffreEmploi();
CSRMappers.MapOffreDTOToEntity(f, of);
candidatEmp.OffreEmploi.Add(of);
}
else
{
//look for offer
var of = CRE.OffreEmploi.Find(f.IDOffre);
if (of != null)
candidatEmp.OffreEmploi.Add(of);
}
}
}
CRE.CandidatEmploi.Add(candidatEmp);
CRE.SaveChanges();
c.IDCandidat = candidatEmp.IDCandidat;
return c;
}
Client side (MVC)
[HttpGet]
public ActionResult PostE(int id)
{
var candidat = new CSRServiceReference.CandidatDTO();
candidat.OffreEmploi = new List<OffreDTO>();
if (id > 0)
{
var offre = CREClient.GetOffre(id);
if(offre != null)
{
candidat.OffreEmploi.Add(offre);
}
}
candidat.Experiences = new List<CSRServiceReference.ExpProDTO>();
candidat.Formations = new List<CSRServiceReference.FormationDTO>();
candidat.ConnInfo = new List<CSRServiceReference.ConnaissInfoDTO>();
candidat.ConnLing = new List<CSRServiceReference.connaissLingDTO>();
return View(candidat);
}
[HttpPost, ActionName("PostE")]
public ActionResult PostEmp(CSRServiceReference.CandidatDTO candidat)
{
if (ModelState.IsValid)
{
candidat.StatutCandidat = "En attente";
var newC = CREClient.CreateCandidat(candidat);
return RedirectToAction("EditCandidat", "Home", new { id = newC.IDCandidat });
}
return View(candidat);
}
But still the association table is empty unfortunately,
I don't know where is the problem exactly: /
Thank you for answering me.
Details
I have 2 tables (Procedures, Surgeons) with a lookup table (ProcSurg) to create a many to many relationship.
scar_Requests scar_Procedures scar_ProcSurg scar_Surgeons
------------- --------------- ------------- -------------
RequestID <> ProcedureID <> ProcedureID(fk) <> SurgeonID
... RequestID SurgeonID(fk) ...
...
A single request can have multiple procedures and each procedure can have multiple surgeons.
Everything saves correctly until I have 2 procedures each that share the same Surgeon.
Error: InvalidOperationException was unhandled
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
I separated out the code for saving this part of the record to try to isolate my problem..
Addprocedures is a class that contains 1 Procedure and a list of Surgeons
class Procedure
{
public scar_Procedures Procedure { get; set; }
public List<scar_Surgeons> Surgeons { get; set; }
public void RemoveSurgeon(int SurgeonID)
{
Surgeons.Remove(Surgeons.Where(x => x.SurgeonID == SurgeonID).FirstOrDefault());
}
public Procedure()
{
Surgeons = new List<scar_Surgeons>();
}
}
Saving code: using DBContext
private void SaveProcSurg()
{
using (MCASURGContext db2 = new MCASURGContext())
{
foreach (Procedure p in AddProcedures)
{
if (p.Procedure.RequestID == 0)
{
p.Procedure.RequestID = ReqID;
}
p.Procedure.scar_Surgeons.Clear();
foreach (scar_Surgeons s in p.Surgeons)
{
if (db2.ChangeTracker.Entries<scar_Surgeons>().Where(x => x.Entity.SurgeonID == s.SurgeonID).FirstOrDefault() == null)
{
db2.scar_Surgeons.Attach(s);
}
p.Procedure.scar_Surgeons.Add(s);
}
if (p.Procedure.ProcedureID == 0)
{
db2.scar_Procedures.Add(p.Procedure);
db2.Entry(p.Procedure).State = System.Data.Entity.EntityState.Added;
}
else
{
db2.scar_Procedures.Attach(p.Procedure);
db2.Entry(p.Procedure).State = System.Data.Entity.EntityState.Modified;
}
}
db2.SaveChanges();
}
}
I've tried several different ways of saving the record and this is the closest I've come to doing it correctly.
I feel like it has something to do with the way I'm attaching the surgeons to the entity and then to the procedure. Any help, idea's or suggestions on where I can find an answer would be great!
I've been searching google endlessly for over a week and I've been trying to wrap my mind around what exactly Entity Framework is doing but I'm still pretty new to this.
Edited 9/24/2013
Sorry this is the complete code snippet from the comments section with the req variable included
//Internal variable
private scar_Requests req;
private List<Procedure> AddProcedures = new List<Procedure>();
//Gets a scar_Request from the DB
private void GetRequest()
{
using (MCASURGContext db = new MCASURGContext())
{
req = db.scar_Requests.Include("scar_Procedures.scar_Surgeons").Include("scar_Status").Include("scar_Users.scar_Service").Where(x => x.RequestID == ReqID).FirstOrDefault();
foreach (scar_Procedures p in req.scar_Procedures) { AddProcedures.Add(new Procedure() { Proc = p, Surgeons = p.scar_Surgeons.ToList() }); }
}
}
Keeping with good form I'll post my answer since I think I figured it out. Maybe it will help someone in the future.
I completely re-wrote the saving and cut out a lot of useless code that I was using before and less calls to the DB. There was other methods that I didn't post above that saved other parts of the record that I condensed into a single method.
Basically I get the record and its joined tables from the DB and iterate through all the fields/joined tables that need to be updated and save it back to the DB. (Seems super obvious now but I tried this way before and I must have had something wrong because it didn't work the first few times I tried it this way.)
I don't know if its 100% correct or written up to normal coding standards and I still have some final tweaking to do before its completely done.
private void SaveProcSurg()
{
using (MCASURGContext db2 = new MCASURGContext())
{
//Get Record from DB
scar_Requests sReq = db2.scar_Requests.Include("scar_Users").Include("scar_Status").Include("scar_Procedures.scar_Surgeons").Where(x => x.RequestID == ReqID).FirstOrDefault();
//Update Record fields
sReq.CreationDate = req.CreationDate == null ? DateTime.Now : req.CreationDate = req.CreationDate;
sReq.DateOfSurgery = dtpDateOfSurgery.Value;
sReq.IsDeleted = false;
sReq.IsScheduled = false;
sReq.LatexAllergy = cbLatexAllergy.Checked;
sReq.ModifiedDate = DateTime.Now;
sReq.MRN = txtMRN.Text;
sReq.PatientName = txtPatientName.Text;
foreach (RadioButton rb in gbPatientType.Controls) if (rb.Checked == true) sReq.PatientType = rb.Text;
sReq.PreOpDiagnosis = txtPreOpDiag.Text;
sReq.PrimarySurgeon = txtPrimarySurgeon.Text;
sReq.PrivateComment = txtPrivateComment.Text;
sReq.PublicComment = txtPublicComment.Text;
sReq.RequestID = ReqID;
sReq.StatusID = req.StatusID;
sReq.UserID = req.UserID;
//Update Users/Status
sReq.scar_Users = db2.scar_Users.Where(x => x.UserID == sReq.UserID).FirstOrDefault();
sReq.scar_Status = db2.scar_Status.Where(x => x.StatusID == req.StatusID).FirstOrDefault();
//Attach to DBContext
db2.scar_Requests.Attach(sReq);
//Update Procedures
foreach (Procedure p in AddProcedures)
{
scar_Procedures pro = sReq.scar_Procedures.Where(x => x.ProcedureID == p.Proc.ProcedureID && p.Proc.ProcedureID != 0).FirstOrDefault();
if (pro != null)
{
pro.EnRecovery = p.Proc.EnRecovery;
pro.IsPrimary = p.Proc.IsPrimary;
pro.Laterality = p.Proc.Laterality;
pro.OrthoFastTrack = p.Proc.OrthoFastTrack;
pro.ProcedureID = p.Proc.ProcedureID;
pro.ProcedureText = p.Proc.ProcedureText;
pro.RequestID = ReqID;
pro.Site = p.Proc.Site;
}
else
{
pro = new scar_Procedures();
pro.EnRecovery = p.Proc.EnRecovery;
pro.IsPrimary = p.Proc.IsPrimary;
pro.Laterality = p.Proc.Laterality;
pro.OrthoFastTrack = p.Proc.OrthoFastTrack;
pro.ProcedureID = p.Proc.ProcedureID;
pro.ProcedureText = p.Proc.ProcedureText;
pro.RequestID = ReqID;
pro.Site = p.Proc.Site; ;
pro.scar_Requests = sReq;
}
//Update Surgeons
pro.scar_Surgeons.Clear();
foreach (scar_Surgeons s in p.Surgeons)
{
pro.scar_Surgeons.Add(db2.scar_Surgeons.Where(x=> x.SurgeonID == s.SurgeonID).FirstOrDefault());
}
}
//Set State and Save
db2.Entry(sReq).State = System.Data.Entity.EntityState.Modified;
db2.SaveChanges();
}
}
public bool SetupEmpty(UserViewModel model, SimsContext db)
{
if (model != null && db != null)
{
// Setup the User
model.User = new T2.Models.User();
model.User.Roles = "";
model.User.ActiveUser = true;
}
return false;
}
Checking that both model and db have been set before starting to use them. Otherwise, if one of them is not set the program could crash.