开发者

linq query for asp.net mvc 3

When selecting to update th开发者_运维技巧at is postponing or cancelling , if the column contains "I" it should return error "cannot update. event already deleted"

public ActionResult Cancel(int ID) { var events = db.Events.Find(ID); return PartialView(events); }

    //
    // POST: /Events/Delete/5

    [HttpPost]

    public ActionResult Cancel(FormCollection Collection)
    {
        var ID = Collection["Event_ID"];
        int intID = int.Parse(ID);
        var events = db.Events.Find(intID);


        // If OK to Cancel , set status to C

        events.Event_Status = "C";
        if (TryUpdateModel(events))
        {
            db.SaveChanges();
            string ConfirmMessage = "Event Successfully Cancelled";
            return RedirectToAction("Confirm", "Admin", new { ConfirmMessage = ConfirmMessage });
        }
        else
        {
            return PartialView(events);
        }
    }


UPDATE:

If you want to throw an error if any of the events are inactive

if (events.Contains(e => e.Status.Equals("I"))
    throw new Exception("Error :: Cannot cancel an event that is already inactive");

If you want to cancel the rest of the events, and warn about the invalid ones:

var invalidEvents = events.Where(e => e.Status.Equals("I")).ToList();
var validEvents = events.Where(e => !invalidEvents.Contains(e)).ToList();

// update valid events

var summary = new { Successes = validEvents, Failures = invalidEvents };

return View(summary);

You want to make the anonymous type a ViewModel so you don't have to cast but you get the general idea. Also, you should probably filter out the invalid events from the list that you generate to cancel them in the first place to avoid this situation though.

PRIOR TO UPDATE:

I don't know exactly what you're trying to do, but an example of a linq query to get the inactive records would be something like this:

var inactiveRecords = from x in dbContext.Records
                      where x.Status.Equals("I")
                      select x;

To throw an error on update of one of these records when "C" or "P" is entered, you would do something like this:

var recordToUpdate = inactiveRecords.FirstOrDefault(); 
var input = Console.ReadLine();

if (recordToUpdate.Status.Equals("I") && (input.Equals("C") || input.Equals("P"))
    throw new Exception("Error :: Cannot update status of an inactive record");

Really though, you shouldn't be using values like "I", "C", or "P" to determine the status of your record, instead you should create a Status table in your database and create a foreign key on the Id of the status.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜