ASP.NET MVC - 表未更新

时间:2016-12-19 19:44:56

标签: asp.net-mvc

我的应用程序旨在允许用户将列表中的即将发生的事件添加到个人日历中。个人日历实现为单个表格,在所有用户之间共享,将string UserID值与int EventID相关联,并为主键单独int UserCalendarID

但是,调用操作时表不会更新;行动发布在下面:

    [HttpPost]
    public IActionResult AddToCalendar(int ID)
    {
        var events = context.Events.ToList();
        Event _e = events.FirstOrDefault(x => x.EventID == ID);
        var calendars = context.Calendars.ToList();
        UserCalendar c = new UserCalendar
        {
            UserID = userManager.GetUserAsync(HttpContext.User).Result.UserName,
            EventID = _e.EventID
        };
        calendars.Add(c);
        context.SaveChanges();
        return View("Index");
    }

作为参考,这是将事件添加到Events表的(工作)代码:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> NewEvent(Models.NewEventViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var newEvent = new Event {
            Artist = await userManager.GetUserAsync(HttpContext.User),
            EventName = model.EventName,
            Time = model.Time,
            Venue = model.Venue,
            GenreID = model.GenreID
        };
        var events = context.Events;
        events.Add(newEvent);
        context.SaveChanges();
        ViewBag.Notification = "Your event has been added.";
        ViewBag.Color = "Green";
    }
    else {
        ViewBag.Notification = "Something went wrong — Event not added.";
        ViewBag.Color = "Red";
    }
    return View("Index");
}

我没有为AddToCalendar使用ViewModel的原因是没有专门针对它的视图;相反,它是由EventDetails页面上的一个表单中的按钮触发的,其定义如下:

@model Event
@{ 
    ViewData["Title"] = "Event Details";
    Event e = ViewBag.Event;
}

<h2>@ViewData["Title"]</h2>

<p><b>Event Name: </b>@e.EventName</p>
<p><b>Artist: </b>@e.Artist.ClientName</p>
<p><b>Date and Time: </b>@e.Time</p>
<p><b>Genre: </b>@e.Genre.GenreName</p>
<p><b>Venue: </b>@e.Venue</p>

@if (ViewBag.isYours)
{
    <a asp-action="DeleteEvent" asp-controller="Home" class="btn btn-danger" asp-route-id=@e.EventID>DELETE</a>
    <a asp-action="EditEvent" asp-controller="Home" class="btn btn-success" asp-route-id=@e.EventID>EDIT</a>
}
<form asp-action="AddToCalendar" asp-controller="Home" asp-route-id=@e.EventID asp-route-returnurl="@ViewData["ReturnUrl"]">
    <input type="submit" value="Add To Your Calendar" class="btn btn-default" />
</form>

我已确认c已添加到calendars。为什么AddToCalendar事件不会导致表更新?

1 个答案:

答案 0 :(得分:1)

请注意,当您从数据库上下文中获取日历时,您正在调用:

var calendars = context.Calendars.ToList();

这会将UserCalendar对象的List加载到内存中。这不会跟踪数据库中的实际日历表。当您添加到Events表时,您将获得如下所示的Events表对象:

var events = context.Events;

注意,没有调用“ToList()”,这意味着您要添加对“Events”的实际上下文对象的引用,而不仅仅是内存中的列表。

如果从调用中删除.ToList()以获取日历,它将跟踪数据库上下文对象,就像在调用中获取Events对象一样。这应该可以解决你的问题。