Add to exisiting Database instance from MVC Controller - c#

Private BookingDB db = new BookingDB();
Private MonthDb mdb = new MonthDB();
if (ModelState.IsValid)
{
String date = (booking.Start_Date).ToString();
var check = from b in mdb.months
where b.BookedDays.Contains(date)
select b;
if (check != null)
{
return View(booking);
}
else
{
booking.Reservation_Owner = User.Identity.Name;
//Add booking.Start_Date to mdb.Entry(check).BookedDays
mdb.SaveChanges();
db.bookings.Add(booking);
db.SaveChanges();
return RedirectToAction("Index");
}
}
I've got this code that on creation of a new booking, will check that no exisiting bookings have already been made on or around that specific day.
if the day to be booked is not already been booked (ie exists under BookedDays in mdb.months) then i wish to add the Start_Date of the booking, to the BookedDays string in the mdb.months database (the mdb.month database is just a list of the 12 months)
at first i tried using mdb.Entry() to add to that specific month instance, however i cannot get it to work.
the error is:
the model does not have a definition for BookedDays
what do?

Your checking that check is null
if (check != null)
{
return View(booking);
}
else
{
and then using check anyway:
check.BookedDays
check is null and therefore does not contain any BookedDays. I'm guessing your null check is the wrong way around and should be
if (check == null)
{
return View(booking);
}
else
{
That said your problem is not well explained so I'm not sure.

Related

C# SetValues, EntityState.Modified not working

I have the following entries in my database:
MeetingID AgendaItem LegistarID Title
48620 3 60710 Comment
48620 5 60615 Extending report date
48620 6 60714 Update on Additional meeting dates
48620 7 59909 Budget Rules & Procedures
48620 8 60703 Update Director name
That I need to update with these values:
MeetingID AgendaItem LegistarID Title
48620 3 60710 Public Comment
48620 5 60769 Briefing by Victor
48620 6 60615 Extending report dates
48620 7 60714 Update on Additional meeting dates
48620 8 60703 Update from Director on new processes
The way I am trying doing this in C#, is as follows:
if (ModelState.IsValid)
{
var errors = new List<string>();
var rowCounter = 1;
using (Entities db = new Entities())
{
foreach (var i in meeting)
{
if (i.MeetingID == 0)
{
// Let the user know this row is bad
errors.Add($"Row {rowCounter}: Missing Meeting ID value. " +
"Verify that the data you are trying to upload meets the required criteria, " +
"and then try to upload your file again." );
break;
}
// Check if LegistarID is missing
if (i.LegistarID == 0)
{
// Check if Agenda Item is present
if (i.AgendaItem == 0)
{
errors.Add($"Row {rowCounter}: Meeting has no LegistarID and no Agenda Item. Please check data.");
break;
}
else
{
i.LegistarID = i.AgendaItem;
}
}
var compositeKey = db.Meeting.Find(i.MeetingID, i.AgendaItem);
if (compositeKey == null)
{
// Add new
db.Meeting.Add(i);
}
else
{
// Serves as an update, or addition of a previously imported dataset
db.Entry(compositeKey).CurrentValues.SetValues(i.MeetingID);
db.Entry(compositeKey).CurrentValues.SetValues(i.AgendaItem);
db.Entry(compositeKey).CurrentValues.SetValues(i.LegistarID);
db.Entry(compositeKey).CurrentValues.SetValues(i.Title);
db.Entry(compositeKey).State = EntityState.Modified;
}
rowCounter++;
}
// If there are errors do not save and return error message
if (errors.Count > 0)
{
return new JsonResult { Data = new { status = false, message = string.Join("\n", errors) } };
}
db.SaveChanges();
status = true;
}
}
else
{
message = string.Format(#"Please, verify that the file you are trying to upload is correctly formatted,
and that the data it contains, meets the expected criteria,
then click the upload button again. \n Thank you!");
return new JsonResult { Data = new { status = status, message = message } };
}
The code for the Add part works well, but the part that updates the record if the composite key is found does not work, the update is not working.
I am not sure if I am doing this the best way, but if there is a better way I am open to change the code, or if I have an error on how I am doing the process, please let me know
Any help is appreciated.
Thank you,
Erasmo
Remove all your calls to SetValues and replace them with single one:
db.Entry(compositeKey).CurrentValues.SetValues(i);
SetValues which accepts object as parameter copies data to entity based on object properties names:
Any property on the object with a name that matches a property name in the entity type and can be read will be copied. Other properties will be ignored.

Does EntityFramework Monitor variables prior to it's declaration and use?

I couldn't understand what was happening when I use Linq.Any() method to check if object contains a specific value, the code throws a NullReferenceException on variable with data prior it's use.
The code below:
public ML.Order FetchOrder(ML.MLDBContext db, long OrderID)
{
if (db == null)
db = new ML.MLDBContext();
//avoided code to fetch the Order details from another system via API
Order apiOrder = api.OrdersGet(OrderID);
//avoided code to test null results
bool isNew = false; //to check if fetched order is new or must be updated on DB
//load from DB
ML.Order dbOrder = db.Orders.Where(o => o.OrderID == apiOrder.id).FirstOrDefault();
if (dbOrder == null)
{
isNew = true;
//avoided code to fill dbOrder with apiOrder data
//Below code check if user bought the same product before
//the error is thrown here but it's not null
string ListingID = apiOrder.order_items.First().item.id;
var previousOrders = db.Orders.Where(order => order.OrderID != apiOrder.id && order.CustomerID == apiOrder.buyer.id && order.SellerID == apiOrder.seller.id).ToList();
foreach (ML.Order prevOrder in previousOrders)
{
if (prevOrder.OrderedItems.Any(i => i.ListingID == ListingID)) //Line who causes the error
{
//code to mask as reordered item
}
}
Some points:
I'm sure "apiOrder.order_items.First().item.id" always have any value.
I'm sure the Order contains the item I'm looking for and the field isn't nullable.
When I comment the line who causes the error, the debug will pass through without errors
To solve this problem, I had to replace Linq.Any() by foreach
foreach (ML.Order prevOrder in previousOrders)
{
foreach (ML.OrderedItem item in prevOrder.OrderedItems)
{
if (item.ListingID == ListingID)
{
//code to mask as reordered item
}
}
}
My doubt is:
Does Linq.Any() or EntityFramework Monitor variables prior to it's declaration and use?
Why the NullreferenceException was trowed on variable prior it usage?
What's the problem using the Linq.Any() method to check the existence of a value inside EF object?

How to check existing record field and compare with post data before change ?

I am very new to MVC and hope someone can assist me.
I have a controller method to save post back data from a form. It has a field called OrderStatus. If the order status value is "Received" then only I want to execute a block of code.
What I am doing in this code is, read the post values and read the EF data again using Find and compare the values. All seems ok but when I try to save the record, it gives me below error.
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I do understand the problem but how can I check the existing values in the database and compare and save.
My code is below
// POST: /Purchasing/Edit/5
[HttpPost]
public ActionResult Edit(PurchaseMaster purchasemaster)
{
if (ModelState.IsValid)
{
if (purchasemaster.OrderStatus == "Received")
{
string myId = purchasemaster.PurchaseId;
//check if the existing status is already set as Received or not
PurchaseMaster pm = db.PurchaseMasters.Find(myId);
if (pm.OrderStatus != "Received") //this will prevent duplicate stock updates
{
//load the items and loop through to update the stock
List<PurchaseDetail> purchasedetails = db.PurchaseDetails.Where(x => x.PurchaseId == myId).ToList();
foreach (PurchaseDetail singleitem in purchasedetails)
{
string itemcode = singleitem.ItemCode;
Item item = db.Items.Find(itemcode);
item.QtyInHand = item.QtyInHand + singleitem.Quantity;
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
}
}
}
db.Entry(purchasemaster).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(purchasemaster);
}
Try this it should work
//don't get this object from database
//PurchaseMaster pm = db.PurchaseMasters.Find(myId);
if (db.PurchaseMasters.Any(x =>x.Id == myId && x.OrderStatus != "Received") {
// Do your stuff
}

linq check if matches null or selected item

I am checking to see if items already match whats in my MSSQL DB. I am using LINQ to update records. I would like to know how i can check if an item is equal to d_0_2 or if its equal to null/empty. How would i go about doing this?
below is my existing code, which partially works. but is failing due to the null/Empty
if (updateProduct.studioId == Convert.ToInt32(d_0_2.SelectedValue)) { }
else { updateProduct.studioId = Convert.ToInt32(d_0_2.SelectedValue);}
Thanks in advance.
I'm not sure if I understood you question correctly, but you want to check if item is null or if not is it studioId equal to d_0_2.SelectedValue
if (updateProduct == null)
{
//create new update product
}
else if (updateProduct.studioId != Convert.ToInt32(d_0_2.SelectedValue))
{
updateProduct.studioId = Convert.ToInt32(d_0_2.SelectedValue);
}
string value = d_0_2.SelectedValue.ToString();
// what if SelectedValue is empty or null?
if (!string.IsNullOrEmpty(value))
return;
// what if product is null?
if (updateProduct != null)
return;
if (updateProduct.studioId != null &&
updateProduct.studioId == Convert.ToInt32(value))
{
// you have product and its id equal to d_0_2.SelectedValue
}
else
{
// studioId not equal to to d_0_2.SelectedValue
updateProduct.studioId = Convert.ToInt32(value);
}

Why would this query be returning null?

I am working on setting up database storage for a game project I am working on for school, and am at the very beginning of doing so. I am using MongoDB at the suggestion of our sponsor. I have successfully implemented inserting a list of names with individual indices, but I cannot get it to return them. The code I am using is as follows.
public string getName(int id) {
var query = Query.EQ("_index", id);
if (Names.FindOne(query) != null) return (Names.FindOne(query)).FirstName;
else return "Error";
}
I have now determined the problem is that the objects aren't being saved. My code for doing so is
public void storeName(string name, int number) {
Name Insert = new Name{FirstName = name, index = number};
var query = Query.EQ("_FirstName", name);
if (Names.FindOne(query) == null) { Names.Save<Name>(Insert); Console.WriteLine(Insert.index+" "+Insert.FirstName); }
else {Console.WriteLine("Bork"); }
}
And the Name object is automapped.
I solved my problem. The index and FirstName fields needed to not have the underscores.

Categories

Resources