MVC Controller not saving data imported in from CSV - asp.net-mvc

I am probably missing something with respect to my understanding of db.savechanges in a MVC controller. So if its something obvious, I apologize in advance.
I am using a MVC controller to import CSV records from a file. The tool I am using is CSVHelper.
I have the following working in code:
1. Calling the file in the view.
2. Executing the actionresult for the importing of records.
The csv file is accessible and is read and turned into a list. And I can tell in debug that all the records are read in to the list and their contents. Here is the code for the actionresult:
public async Task<ActionResult> ImportRecords(HttpPostedFileBase file)
{
string path = null;
List<ReportsToRecord> RTRs = new List<ReportsToRecord>();
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\uploads\\" + fileName;
file.SaveAs(path);
var csv = new CsvReader(new StreamReader(path));
var RTRecordlist = csv.GetRecords<ReportsToRecord>();
foreach (var r in RTRecordlist)
{
ReportsToRecord RTR = new ReportsToRecord();
RTR.Id = r.Id;
RTR.REPORTING_ID = r.REPORTING_ID;
RTR.TITLE = r.TITLE;
RTR.NAME = r.NAME;
RTR.REPORTS_TO_ID = r.REPORTS_TO_ID;
RTR.EMPLOYEE_ID = r.EMPLOYEE_ID;
RTRs.Add(RTR);
}
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
}
catch
{
ViewData["error"] = "Upload Failed";
}
return View();
}
When I debug the RTRs.add line it does show all the records successfully read. However the await db.savechangesasync does NOT result in these records being saved.
The actual model name for the records being saved ( in Entity Framework) is ReportsToRecord with the controller name being ReportsToRecordsController.
Can anyone see in my code why the RTRs object does contain the records but these do not get saved into the ReportsToRecord model?
The only other thing I can share is that the csv file also contains the key column 'Id'. I dont know whether this is allowed or not for the savechanges operation on the imported records.Normally these keys are generating automatically in m y MVC apps.
As it stands no error comes up. The csv file's records get read in but just dont seem to be saved back to the database.
Its the typical story.Since no error comes up even in debug, the code is doing exactly what its been asked to do- BUT not what its 'Supposed to' do - which is to carry out the saving to the database.
Any insights would be appreciated. I suspect I am making some stupid error.

dumb error
i changed RTRs.Add(RTR); to
db.ReportsToRecords.Add(RTR);
and it worked

Related

Convert DataTable to Entity Objects and add to Table

I am quite new to Programming/MVC, so apologies for any incorrect terminology.
In my MVC application using Entity Framework, I am struggling to create some functionality that allows a user to upload a CSV file, parse it, and add it to my database (generated by code first).
I have a Project Model, and I want a user to be able to upload a CSV file of Deliverables for specific Projects. I will then have a View that displays Project Details, and a full list of all Deliverables as well.
Following a pretty straight forward tutorial, I have the CSV parser in my view which presents the DataTable after parsing. The View renders fine, and the this is the controller I am using:
public ActionResult Upload()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
if (upload.FileName.EndsWith(".CSV"))
{
Stream stream = upload.InputStream;
DataTable csvTable = new DataTable();
using (CsvReader csvReader = new CsvReader(new StreamReader(stream), true))
{
csvTable.Load(csvReader);
}
return View(csvTable);
}
else
{
ModelState.AddModelError("File", "This file format is not supported");
return View();
}
}
else
{
ModelState.AddModelError("File", "Please Upload Your file");
}
}
return View();
}
Tutorial: http://techbrij.com/read-csv-asp-net-mvc-file-upload
I now can't for the life of me understand how I can now put this Datatable into my Deliverables table, whilst referencing the specific Project the Deliverables are for. For example, how can the code know that the deliverables in the CSV file are for Project#123 and not Project#122...
I am hoping for nudge in the right direction, and really appreciate any assistance.

Web API 2.2 - OData v4 (Manually Parsing Uri + Expanding)

I have an ODataController with a Get method as such:
public IHttpActionResult Get(ODataQueryOptions<MyModel> queryOptions) {
IQueryable<MyModel> models = _Models.AsQueryable(); // _Models Defined in Controller as List<MyModel> and is already populated with nested data for both .LevelOne and .LevelOne.LevelTwo which are two other Lists.
Uri fullrequest = Request.GetRequestContext().Url.Request.RequestUri; // http://localhost:8080/odata/Root?$expand=LevelOne($expand=LevelTwo)
Uri serviceroot = new Uri(controller.GetLeftPart(UriPartial.Path).Replace("/Root", "")); // http://localhost:8080/odata
String metadata = service + "/$metadata"; // http://localhost:8080/odata/$metadata
IEdmModel model = EdmxReader.Parse(XmlTextReader.Create(metadata));
ODataUriParser parser = new ODataUriParser(model, serviceroot, fullrequest);
SelectExpandClause selectAndExpand = parser.ParseSelectAndExpand();
//Only one of the two below lines is ever commented in...
Request.ODataProperties().SelectExpandClause = queryOptions.SelectExpand.SelectExpandClause; // This line will work
Request.ODataProperties().SelectExpandClause = selectAndExpand; // This line will not work
return Ok(models);
}
using my manually parsed selectAndExpand does not expand the dataset, but using the predefined queryOptions one does. Any ideas why? Both objects appear to contain the same information while viewed in the debugger, but I must be missing something. I want to be able to parse the URI myself, without the need for the ODataQueryOptions at all.
What I ended up doing, was building a new ODataQueryOptions object based off the original request, and then pulling just the SelectExpandClause from that. It doesn't answer my initial question, but it is a somewhat working solution for not having to pass in a ODataQueryOptions parameter. See my Code below:
public IHttpActionResult Get() {
//Get Queryable Item (in this case just a list made queryable)
IQueryable<MyModel> models = _Models.AsQueryable();
//Create new ODataQueryContext based off initial request (required to create ODataQueryOptions)
ODataQueryContext selectAndExpandContext = new ODataQueryContext(Request.ODataProperties().Model, typeof(MyModel), Request.ODataProperties().Path);
//Create new ODataQueryOptions based off new context and original request
ODataQueryOptions<Employee> selectAndExpandOptions = new ODataQueryOptions<Employee>(selectAndExpandContext, Request);
//Attach Select + Expand options to be processed
if (selectAndExpandOptions.SelectExpand != null) {
Request.ODataProperties().SelectExpandClause = selectAndExpandOptions.SelectExpand.SelectExpandClause;
}
return Ok(models);
}

Error copying a record from one entity to another using Entity Framework and Automapper

I am trying to move a record from one table into another matching (almost) table using EF5, MVC, and Automapper.
This code is what I am using:
In My Global Application_Start
//Create Map and manually map StatusCode to Status
Mapper.CreateMap<InstitutionStaging, InstitutionStaging_Archive>()
.ForMember(dest => dest.Status,o =>o.MapFrom(src=>src.StatusCode));
In my Controller
private MyContext db = new MyContext();
Public ActionResult ArchiveMe(int id = 0){
var institutionstaging = db.InstitutionStagings.Find(id);
if (institutionstaging == null)
{
return HttpNotFound();
}
if (ModelState.IsValid)
{
var institutionArchive = Mapper.Map<InstitutionStaging, InstitutionStaging_Archive>(institutionstaging);
//Set Archive date to now.
institutionArchive.ArchiveDate = DateTime.Now;
//Error happens on the next line
db.InstitutionStaging_Archives.Add(institutionArchive);
db.InstitutionStagings.Remove(institutionstaging);
db.Entry(institutionArchive).State = EntityState.Added;
//Commit the changes
var result = db.SaveChanges();
}
}
When it hits the line marked "Error happens here==>" I get the following error message.
{"The entity type InstitutionStaging_Archive is not part of the model for the current context."}
The MyContext contains DbSets for both InstitutionStaging and InstitutionStaging_Archive.
Any idea what is happening?
TIA
J
This error isn't typically a problem with AutoMapper, but rather a problem with your Entity Framework model setup.
It can be because you are using the wrong connection string, or it can be because you don't have the model mapped correctly.
Since we don't know what your model is, what your database looks like, or how your mappings are.. can't help much beyond that.
To prove it to yourself, just comment out the automapper stuff and do it by hand, and I'm pretty sure you'll get the same error.

How do I gracefully reattach an Entity Framework 5 POCO structure and save it?

I am making an MVC4 web application using Entity Framework 5 (Database-first with generated POCOs) for data access.
In the app, the user goes through several screens, creating or editing a document (called a 'case study'). When they arrive at the final screen, their document exists as a CaseStudy POCO in memory, and everything is great until it is time to save this structure to the database.
To store the document, I have defined several database tables, which in turn map to EF POCOs used by the business layer, which is then consumed by the MVC controllers. As such, short-lived DbContexts are used to retrieve POCOs and store them in session between requests.
As a result, the save screen must save the contents of this POCO that has navigational properties to existing table data (Category, Layout, and Sections tables), and also added or updated data (CaseStudySections and the CaseStudy itself). So all of the POCOs are either new, or the context used to retrieve them has long been disposed. In other words, they are all 'detached'.
What is unusual about this post is that I already have a working solution in hand. The problem is that it is bulky, brittle, and inelegant. I am posting the code below. Note the iteration through sub-collections, the explicit adds and attaches, having to get an entry object and mark individual properties as modified just so they will be updated, and the awful song and dance at the end to get the AdditionalMaterials collection synced up. If this is what is required to deal with detached POCOs in EF5 I will be disappointed.
Am I missing something here? Is this consistent with best practices? Is there a more graceful and/or concise way to attach a structure of POCOs and insert/update?
The code to save a case study:
public void SaveCaseStudy(CaseStudy caseStudy)
{
foreach (var s in caseStudy.CaseStudySections)
{
this.Entities.Sections.Attach(s.Section);
if (s.CreatedByRefId == default(Guid))
{
s.CreatedByRefId = this.UserRefId;
s.CreatedTime = DateTime.Now;
this.Entities.CaseStudySections.Add(s);
}
else
{
this.Entities.CaseStudySections.Attach(s);
var entry = this.Entities.Entry(s);
entry.Property(e => e.TextData).IsModified = true;
entry.Property(e => e.BinaryData).IsModified = true;
}
s.LastModifiedByRefId = this.UserRefId;
s.LastModifiedTime = DateTime.Now;
}
foreach (var m in caseStudy.AdditionalMaterials)
{
if (m.CreatedByRefId == default(Guid))
{
m.CreatedByRefId = this.UserRefId;
m.CreatedTime = DateTime.Now;
this.Entities.AdditionalMaterials.Add(m);
}
else
{
this.Entities.AdditionalMaterials.Attach(m);
}
m.LastModifiedByRefId = this.UserRefId;
m.LastModifiedByTime = DateTime.Now;
}
this.Entities.Layouts.Attach(caseStudy.Layout);
this.Entities.Categories.Attach(caseStudy.Category);
if (caseStudy.CreatedByRefId != default(Guid))
{
this.Entities.CaseStudies.Attach(caseStudy);
var entry = this.Entities.Entry(caseStudy);
entry.Property(e => e.CaseStudyName).IsModified = true;
entry.Property(e => e.CaseStudyTitle).IsModified = true;
}
else
{
this.Entities.CaseStudies.Add(caseStudy);
caseStudy.CreatedByRefId = this.UserRefId;
caseStudy.CreatedTime = DateTime.Now;
}
caseStudy.LastModifiedByRefId = this.UserRefId;
caseStudy.LastModifiedTime = DateTime.Now;
if (caseStudy.CaseStudyStatus != (int)CaseStudyStatus.Personalized)
{
caseStudy.CaseStudyStatus = (int)CaseStudyStatus.PendingApproval;
}
caseStudy.ApprovedByRefId = null;
caseStudy.ApprovedTime = null;
this.Entities.SaveChanges();
var existingAdditionalMaterialRefIds = caseStudy.AdditionalMaterials
.Select(m => m.AdditionalMaterialRefId)
.ToArray();
var additionalMaterialsToRemove = this.Entities.AdditionalMaterials
.Where(m =>
m.CaseStudyRefId == caseStudy.CaseStudyRefId &&
!existingAdditionalMaterialRefIds.Contains(m.AdditionalMaterialRefId))
.ToArray();
foreach (var additionalMaterialToRemove in additionalMaterialsToRemove)
{
this.Entities.AdditionalMaterials.Remove(additionalMaterialToRemove);
}
this.Entities.SaveChanges();
}
In general it is what you have to do. You must tell EF about each change you want to perform when attaching detached object graph. I don't say that your code cannot be simplified but you will still have to deal with every entity and setting its state if you want it to be added or modified.
Here is little bit older but still valid answer about the topic - in short nothing has changes since I wrote it, only new DbContext API was created which still sits on top of the old API. The best description of this topic I have seen so far is in book Programming Entity Framework: DbContext.
How about just doing:
db.CaseStudies.Attach(caseStudy);
db.Entry(caseStudy).State = EntityState.Modified;
db.SaveChange();
That will save all changes in your model to the db.

Why is my code not able to update the database?

I am having trouble saving my entities after updating them. I can add new entities like this: add(student); but if I tried this:
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("someView");
}
I get this error message:
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException was unhandled by user code
Message=Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or
deleted since entities were loaded. Refresh ObjectStateManager
entries.
Here’s my controller method:
[HttpPost]
public ActionResult ClassAttendance(InstructorIndexData viewModel, FormCollection frmcol)
{
var instructorData = new InstructorIndexData();
string[] AllFstMNames = frmcol["item.Student.FirstMidName"].Split(',');
string[] AllLstNames = frmcol["item.Student.LastName"].Split(',');
string[] AllAddresses = frmcol["item.Student.Address"].Split(',');
string[] AllEnrollmentDates = frmcol["item.Student.EnrollmentDate"].Split(',');
//more of the same code…
var student = new Student();
var enrollment = new Enrollment();
for ( int i = 0; i < AllFstMNames.Count(); i++)
{
student.FirstMidName = AllFstMNames[i];
student.LastName = AllLstNames[i];
student.Address = AllAddresses[i];
student.EnrollmentDate = Convert.ToDateTime(AllEnrollmentDates[i]);
if (!string.IsNullOrEmpty(frmcol["item.Grade"]))
{
enrollment.Grade = Convert.ToInt32(AllGrades[i]);
}
enrollment.StudentID = Convert.ToInt32(AllStudentIds[i]);
enrollment.attendanceCode = Convert.ToInt32(AllAttendanceCodes[i]);
enrollment.classDays = AllclassDays[i];
enrollment.CourseID = Convert.ToInt32 (AllCourseIds[i]);
//update rows
}
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("someView");
}
Can you help me with just being able to update values in the database?
While I was looking at the code here, my initial thought is that it doesn't seem quite right to have a for loop that updates the student and enrollment objects multiple times and then to have only one call to db.SaveChanges outside the loop. This is concerning because only the last iteration of the for loop will be applied when the data is saved to the database. (You have a comment to "update rows" at the end of the for loop - perhaps some code is missing or misplaced?)
Then, I started thinking about why it would be necessary to manually set the Entry(...).State property. Wouldn't the db automatically know that an object is modified and needs to be saved? That lead me to this question: Where is db defined? What technology stack is being used there?
Finally, after making an assumption that the db object might work something like the MS LINQ-to-SQL feature, I noticed that the the student object is newly instantiated before the for loop. This is fine for inserting new data, but if you are wanting to update existing data, I believe you need to first get a copy of the object from the database and then update the properties. This allows the db object to monitor the changes (again, assuming that it has this capability). (If this is not the case, then it leads me to wonder how the db will know which record in the database to update since you are not setting anything that appears to be a primary key, such as StudentId, on the student object in the loop.)

Resources