Performance issue when performing operations on entity objects - c#

Im facing performance issue in below code in multiple foreach loops. First im getting a list of ReturnDetails and then based on detail id get the HandlingInfo object. Then based on value of action, update the ReturnsDetail Object again.
It take more than a minute for loading 3000 records of ReturnsDetail. While debugging locally, it runs for infinite amount of time.
Please let me know in anyway i can refactor this code .
Thanks for your help.
lstReturnsDetail = dcReturnsService.GetReturnDetailsInfo(header_id);
List<HandlingInfo> lstHandlingInfo = null;
foreach (ReturnsDetail oReturnsDetail in lstReturnsDetail)
{
using (DCReturns_Entities entities = new DCReturns_Entities())
{
lstHandlingInfo = entities.HandlingInfoes.Where(f => f.detail_id == oReturnsDetail.id).ToList();
if(lstHandlingInfo != null)
{
foreach (HandlingInfo oHandlingInfo in lstHandlingInfo)
{
if (oHandlingInfo.action == "DST")
{
oReturnsDetail.destroy += Convert.ToInt32(oHandlingInfo.qty);
}
else if (oHandlingInfo.action == "SHP")
{
oReturnsDetail.to_shop += Convert.ToInt32(oHandlingInfo.qty);
}
else if (oHandlingInfo.action == "RBX")
{
oReturnsDetail.in_stock += Convert.ToInt32(oHandlingInfo.qty);
}
}
}
}
oReturnsDetail.received_qty = oReturnsDetail.destroy + oReturnsDetail.to_shop + oReturnsDetail.in_stock;
}
dgReturnsDetail.DataSource = lstReturnsDetail.OrderByDescending(g => g.id).ToList();
Session[DCReturnsConstants.Returns_Detail_Entity] = lstReturnsDetail;
dgReturnsDetail.DataBind();

this is su-do code! but you should get the jist.
//modify this to return all of them into mem, and then filter on this...
//if it can not be done here then do below..
var lstReturnsDetail = dcReturnsService.GetReturnDetailsInfo(header_id);
//then create a list here which fetches all,
List<[type]> somelist
List<int> listId = lstReturnsDetail.select(x=>x.id).tolist();
using (var db = new DCReturns_Entities())
{
somelist = db.HandlingInfoes.Where(f => listId.Contains( f.detail_id)).ToList();
}
foreach (ReturnsDetail oReturnsDetail in lstReturnsDetail)
{
//performance issue is here
//using (DCReturns_Entities entities = new DCReturns_Entities())
//{
// lstHandlingInfo = entities.HandlingInfoes.Where(f => f.detail_id == oReturnsDetail.id).ToList();
//}
//insead fetach all before, into mem and filter from that list.
var lstHandlingInfo = somelist.Where(f => f.detail_id == oReturnsDetail.id).ToList();
//code ommited for reaablity
}
//code ommited for reaablity

Related

How to speed up workflow with database .Net

I have simple controller that return list of products.It is take about 5-7sec to return the data for the first time,and then 50-80ms ,but only if i run it immediately(10-30sec) after first one ,if i will run it after 2-3min it will be again 5-7s.
I dont store this list in cache,sow i cant understand why only first time it takes 5sec,and then 50ms.
Important:test that i have made is not on localhost,it is on the production server.On localhost it takes 50ms
How can i speed up?
Do i need to make any change in my code? Or IIS?
My code
public List<PackageModel> GetPromotionOrDefaultPackageList(string domain)
{
List<DBProduct> DBPackageList = new List<DBProduct>();
List<PackageModel> BllPackageList = new List<PackageModel>();
try
{
using (CglDomainEntities _entities = new CglDomainEntities())
{
DBPackageList = _entities.DBProducts
.Where(x =>
x.ProductGroup.Equals(domain + "-package")
&& x.IsPromotionProduct == true)
.ToList();
if (DBPackageList.Count == 0)
{
DBPackageList = _entities.DBProducts
.Where(x =>
x.ProductGroup.Equals(domain + "-package")
&& x.IsBasicProduct == true)
.ToList();
}
}
PackageModel bllPackage = new PackageModel();
foreach (DBProduct dbProduct in DBPackageList)
{
bllPackage = new PackageModel();
bllPackage.Id = dbProduct.Id;
bllPackage.ProductId = dbProduct.ProductId;
bllPackage.IsPromotionProduct = dbProduct.IsPromotionProduct.HasValue ? dbProduct.IsPromotionProduct.Value : false;
bllPackage.ProductName = dbProduct.ProductName;
bllPackage.ProductDescription = dbProduct.ProductDescription;
bllPackage.Price = dbProduct.Price;
bllPackage.Currency = dbProduct.Currency;
bllPackage.CampaignId = dbProduct.CampaignId;
bllPackage.PathToProductImage = dbProduct.PathToProductImage;
bllPackage.PathToProductPromotionImage = dbProduct.PathToProductPromotionImage;
bllPackage.PathToProductInfo = dbProduct.PathToProductInfo;
bllPackage.CssClass = dbProduct.CssClass;
BllPackageList.Add(bllPackage);
}
return BllPackageList;
}
catch (Exception ex)
{
Logger.Error(ex.Message);
return BllPackageList;
}
}

How to incorporate criteria in Where method?

I want to ask about the WHERE condition in my search command. I'm calling web service (API) during searching and I want to put WHERE statement in my code but there's an error.
private async Task CallApi(string searchText = null)
{
long lastUpdatedTime = 0;
long.TryParse(AppSettings.ComplaintLastUpdatedTick, out lastUpdatedTime);
var currentTick = DateTime.UtcNow.Ticks;
var time = new TimeSpan(currentTick - lastUpdatedTime);
if (time.TotalSeconds > 1) {
int staffFk = Convert.ToInt32(StaffId);
var result = await mDataProvider.GetComplaintList(lastUpdatedTime, mCts.Token, staffFk);
if (result.IsSuccess)
{
// Save last updated time
AppSettings.ComplaintLastUpdatedTick = result.Data.Updated.ToString();
// Store data into database
if ((result.Data.Items != null) &&
(result.Data.Items.Count > 0))
{
var datas = new List<Complaint>(result.Data.Items);
**if (!string.IsNullOrEmpty(searchText))
{
datas = datas.Where(i => i.Description.Contains(searchText)
&& (i.SupervisorId.Equals(StaffId))
|| (i.ProblemTypeName.Contains(searchText)));
}
else
{
datas = datas.Where(i => i.SupervisorId.Equals(StaffId));
}**
Datas = new ObservableCollection<Complaint>(datas);
}
}
else if (result.HasError)
{
await mPageDialogService.DisplayAlertAsync("Error", result.ErrInfo.Message, "OK");
}
}
}
Both assignments of datas in the if ... else causes System.Collections.Generic.IEnumerable<ECS.Features.Complaints.Complaint>' to 'System.Collections.Generic.List<ECS.Features.Complaints.Complaint>'. An explicit conversions exists (are you missing a cast?) compilation errors:
I don't know how to use the WHERE condition there. Please help me. Thank you in advance for your concern.
datas is a List<Complaint> but you try to reassign it to IEnumerable<Complaint> with the Where statement. Add a ToList() after the Where to maintain type,
Or you could just declare datas as IEnumerable<Complaint>
IEnumerable<Complaint> datas = new List<Complaint>(result.Data.Items);
Issue is that datas is defined as being a List<Complaint>, and the return type of datas.Where(...) is an IEnumerable/IQueryable.
You could do:
datas = datas.Where(i => i.SupervisorId.Equals(StaffId)).ToList();
Complete code:
private async Task CallApi(string searchText = null)
{
long lastUpdatedTime = 0;
long.TryParse(AppSettings.ComplaintLastUpdatedTick, out lastUpdatedTime);
var currentTick = DateTime.UtcNow.Ticks;
var time = new TimeSpan(currentTick - lastUpdatedTime);
if (time.TotalSeconds > 1) {
int staffFk = Convert.ToInt32(StaffId);
var result = await mDataProvider.GetComplaintList(lastUpdatedTime, mCts.Token, staffFk);
if (result.IsSuccess)
{
// Save last updated time
AppSettings.ComplaintLastUpdatedTick = result.Data.Updated.ToString();
// Store data into database
if ((result.Data.Items != null) &&
(result.Data.Items.Count > 0))
{
var datas = new List<Complaint>(result.Data.Items);
if (!string.IsNullOrEmpty(searchText))
{
datas = datas.Where(i => i.Description.Contains(searchText)
&& (i.SupervisorId.Equals(StaffId))
|| (i.ProblemTypeName.Contains(searchText))).ToList();
}
else
{
datas = datas.Where(i => i.SupervisorId.Equals(StaffId)).ToList();
}
Datas = new ObservableCollection<Complaint>(datas);
}
}
else if (result.HasError)
{
await mPageDialogService.DisplayAlertAsync("Error", result.ErrInfo.Message, "OK");
}
}
}
You will then also have an error on the next line, Datas = new ObservableCollection becasue Datas is not defined, and if you meant datas, again, it will not be the List<> that you initially defined.

Getting The Wait Operation Timeout Exception for a query from Skip Value 100

I am writing a small data migration tools from one big database to another small database. All of the others data migration method worked satisfactorily, but the following method has given an exception from the SKIP VALUE IS 100. I run this console script remotely as well as inside of the source server also. I tried in many different was to find the actual problem what it is. After then I found that only from the SKIP VALUE IS 100 it is not working for any TAKE 1,2,3,4,5 or ....
Dear expertise, I don't have any prior knowledge on that type of problem. Any kind of suggestions or comments is appreciatable to resolve this problem. Thanks for you time.
I know this code is not clean and the method is too long. I just tried solve this by adding some line of extra code. Because the problem solving is my main concern. I just copy past the last edited method.
In shot the problem I can illustrate with this following two line
var temp = queryable.Skip(90).Take(10).ToList(); //no exception
var temp = queryable.Skip(100).Take(10).ToList(); getting exception
private static void ImporterDataMigrateToRmgDb(SourceDBEntities sourceDb, RmgDbContext rmgDb)
{
int skip = 0;
int take = 10;
int count = sourceDb.FormAs.Where(x=> x.FormAStateId == 8).GroupBy(x=> x.ImporterName).Count();
Console.WriteLine("Total Possible Importer: " + count);
for (int i = 0; i < count/take; i++)
{
IOrderedQueryable<FormA> queryable = sourceDb.FormAs.Where(x => x.FormAStateId == 8).OrderBy(x => x.ImporterName);
List<IGrouping<string, FormA>> list;
try
{
list = queryable.Skip(skip).Take(take).GroupBy(x => x.ImporterName).ToList();
//this line is getting timeout exception from the skip value of 100.
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
sourceDb.Dispose();
rmgDb.Dispose();
sourceDb = new SourceDBEntities();
rmgDb = new RmgDbContext();
skip += take;
continue;
}
if (list.Count > 0)
{
foreach (var l in list)
{
List<FormA> formAs = l.ToList();
FormA formA = formAs.FirstOrDefault();
if (formA == null) continue;
Importer importer = formA.ConvertToRmgImporterFromFormA();
Console.WriteLine(formA.FormANo + " " + importer.Name);
var importers = rmgDb.Importers.Where(x => x.Name.ToLower() == importer.Name.ToLower()).ToList();
//bool any = rmgDb.Importers.Any(x => x.Name.ToLower() == formA.ImporterName.ToLower());
if (importers.Count() == 1)
{
foreach (var imp in importers)
{
Importer entity = rmgDb.Importers.Find(imp.Id);
entity.Country = importer.Country;
entity.TotalImportedAmountInUsd = importer.TotalImportedAmountInUsd;
rmgDb.Entry(entity).State = EntityState.Modified;
}
}
else
{
rmgDb.Importers.Add(importer);
}
rmgDb.SaveChanges();
Console.WriteLine(importer.Name);
}
}
skip += take;
}
Console.WriteLine("Importer Data Migration Completed");
}
I have fixed my problem by modifying following code
var queryable =
sourceDb.FormAs.Where(x => x.FormAStateId == 8)
.Select(x => new Adapters.ImporterBindingModel()
{
Id = Guid.NewGuid().ToString(),
Active = true,
Created = DateTime.Now,
CreatedBy = "System",
Modified = DateTime.Now,
ModifiedBy = "System",
Name = x.ImporterName,
Address = x.ImporterAddress,
City = x.City,
ZipCode = x.ZipCode,
CountryId = x.CountryId
})
.OrderBy(x => x.Name);

Problems with adding attachments to a workItem (changing dates)

I have a task to relocate work items from one TFS project to another within one TFS collection. All history and dates have to be identical to the original item. I read a lot information and have done a lot of work. I have almost completed the task but found one crucial issue. After saving of a new item which have been copied from original one I lost my attachments in revisions. Thus I can relocate item only once, after next attempt attachments will be lost.
There is my approach to copy items:
First of all I read that article about changing creation date and changed date: TFS API Change WorkItem CreatedDate And ChangedDate To Historic Dates.
Then I had next code:
var type = project.WorkItemTypes[itemToCopy.Type.Name];
var newWorkItem = new WorkItem(type);
List<Revision> revisions = item.Revisions.Cast<Revision>().OrderBy(r => r.Index).ToList();
var firstRevision = revisions.First();
revisions.Remove(firstRevision);
SetFields(newWorkItem, firstRevision.Fields, includeAreas);
result = Save(newWorkItem);
if (result != string.Empty)
throw new Exception(result);
newWorkItem = tfsManager.GetWorkItemStore().GetWorkItem(newWorkItem.Id);
var changed = firstRevision.Fields.Cast<Field>().First(f => f.ReferenceName == "System.ChangedDate").Value;
var created = firstRevision.Fields.Cast<Field>().First(f => f.ReferenceName == "System.CreatedDate").Value;
var changedDate = (DateTime)changed;
var createdDate = (DateTime)created;
newWorkItem.Fields["System.CreatedDate"].Value = createdDate;
newWorkItem.Fields["System.ChangedDate"].Value = changedDate.AddSeconds(1);
result = Save(newWorkItem);
if (result != string.Empty)
throw new Exception(result);
var attachments = firstRevision.Attachments.Cast<Attachment>().ToList();
var attachMap = new Dictionary<int, Attachment>();
if (attachments.Count > 0)
AddAttachments(newWorkItem, firstRevision.Attachments.Cast<Attachment>().ToList(), attachMap);
else
{
result = Save(newWorkItem);
if (result != string.Empty)
throw new Exception(result);
}
ApplyRevisions(newWorkItem, revisions, attachMap, includeAreas);
return newWorkItem;
The method "SetFields" copies all editable fields from the original work item to a new work item.
The method "Save" simply saves the work item and collect all info about mistakes during save process.
The method "ApplyRevisions" simple enumerate all revisions and copy fields and attachments. It looks like:
private void ApplyRevisions(WorkItem toItem,
List<Revision> revisions, Dictionary<int,
Attachment> attachMap,
bool includeAreas)
{
foreach (var revision in revisions.OrderBy(r => r.Index))
{
SetFields(toItem, revision.Fields, includeAreas);
AddAttachments(toItem, revision.Attachments.Cast<Attachment>().ToList(), attachMap);
AddChangesetLinks(toItem, revision.Links.Cast<Link>().ToList());
var result = Save(toItem);
if (result != string.Empty)
{
SetFields(toItem, revision.Fields, includeAreas);
result = Save(toItem);
if (result != string.Empty)
{
throw new Exception(result);
}
}
}
}
And the main part is how I copy attachments:
private void AddAttachments(WorkItem item, IList<Attachment> attaches, Dictionary<int, Attachment> attachMap)
{
var guid = Guid.NewGuid();
var currentAttaches = item.Attachments.Cast<Attachment>().ToList();
var files = new List<string>();
try
{
item.Open();
foreach (var attach in attaches)
{
if (attachMap.ContainsKey(attach.Id))
{
var id = attachMap[attach.Id].Id;
if (currentAttaches.Any(a => a.Id == id))
continue;
}
var bytes = tfsManager.TfsWebClient.DownloadData(attach.Uri);
var tempFile = CreateFileName(guid, attach.Name);
files.Add(tempFile);
if (bytes != null && bytes.Length > 0)
File.WriteAllBytes(tempFile, bytes);
else
{
File.Create(tempFile).Dispose();
}
var attachInfo = new AttachmentInfo(tempFile);
attachInfo.FieldId = 50;
attachInfo.CreationDate = attach.CreationTimeUtc;
//attachInfo.LastWriteDate = attach.LastWriteTimeUtc;
attachInfo.Comment = attach.Comment;
//attachInfo.AddedDate = attach.AttachedTimeUtc;
var newAttach = Attachment.MakeAttachment(item, attachInfo);
item.Attachments.Add(newAttach);
if (!attachMap.ContainsKey(attach.Id))
attachMap[attach.Id] = newAttach;
}
foreach (var attach in currentAttaches)
{
var id = attachMap.First(pair => pair.Value.Id == attach.Id).Key;
if (attaches.All(a => a.Id != id))
{
item.Attachments.Remove(attach);
}
}
var result = Save(item);
if (result != string.Empty)
throw new Exception(result);
}
finally
{
if (files.Count > 0)
{
foreach (var file in files)
{
File.Delete(file);
}
RemoveTempFolder(guid);
}
}
}
After copying item and retrieving it from TFS property "Attachments" in property "Revisions" is empty. I guess, that the problem is in different dates... But do not know how to solve it...
Sorry for enormous amount of code. It is my first question here.
P.S.
I have digged deeper in the question and found out that the problem in AuthorizedAddedDate of AttachmentInfo. There is a comparison of this date and ChangeDate of the particular revision during of process of filling Attachments. See code below:
DateTime asof = (DateTime) changedDate;
foreach (LinkInfo linkInfo in this.m_linksData)
{
if (linkInfo.AuthorizedAddedDate <= asof && asof < linkInfo.AuthorizedRemovedDate)
yield return linkInfo;
}
ChangedDate we can change and I change it during of processing of revisions. Unfortunately, I do not know how to change AuthorizedAddedDate of AttachmentInfo... Even if I change it, the value is the same after next load of the work item... It seems that this value is prohibited for changing(
Yep, it seems that I have found the answer. At least this solution helped me. Sorry, that I have not posted it immediately. The process of adding attachment looks like that:
var attachInfo = new AttachmentInfo(tempFile);
attachInfo.AddedDate = attach.AddedDate;
attachInfo.CreationDate = attach.CreationDate;
attachInfo.Comment = string.Format(#"{0} (from attachId={1})", attach.Comment, attach.Id);
attachInfo.RemovedDate = attach.RemovedDate;
attachInfo.FieldId = 50;
itemTo.LinkData.AddLinkInfo(attachInfo, itemTo);
Where "tempFile" is a file which we want to attach (in my case it has been copied from another WorkItem) and "attach" is a container for information about AttachmentInfo. "itemTo" is a target WorkItem where we want to add attachment.
If you need more detail or you want me to clarify any moments, please, let me know.
P.S. It is important to remember about time zones when setting AddedDate, CreationDate and RemovedDate.

Updating multiple records that share a many to many relationship fails

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();
}
}

Categories

Resources