【问题标题】:My list is empty after adding an object to the list将对象添加到列表后,我的列表为空
【发布时间】:2014-02-09 06:03:25
【问题描述】:

我正在编写一个 MVC4 C# 互联网应用程序,当我成功地将一个对象保存到一个列表时,当我在另一个函数中获得该列表的列表时,该列表是空的。

这是我的代码:

public class House
{
    public House()
    {
        Rooms = new List<Room>();
    }

    [Key]
    public int id { get; set; }
    public int StreetNumber { get; set; }
    public string StreetName { get; set; }
    public string City { get; set; }

    public List<Room> Rooms { get; set; }
}

public class Room
{
    [Key]
    public int id { get; set; }
    public int RoomNumber { get; set; }
    public string RoomOwnersName { get; set; }
}

public class DatabaseContext : DbContext
{
    public DbSet<House> Houses { get; set; }
    public DbSet<Room> Rooms { get; set; }
}

这是我创建房间并将其添加到房屋的代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, Room room)
{
    if (ModelState.IsValid)
    {
        House houseToAddRoomsTo = db.Houses.Where(h => h.id == id).FirstOrDefault();
        houseToAddRoomsTo.Rooms.Add(room);
        db.SaveChanges();
        return RedirectToAction("Index", id);
    }

    return View(room);
}

这是我获取房屋中房间列表的代码:

public ActionResult Index(int id)
{
    RoomsViewModel roomsViewModel = new RoomsViewModel();
    roomsViewModel.HouseID = id;
    roomsViewModel.Rooms = db.Houses.Where(h => h.id == id).First().Rooms.ToList();
    return View(roomsViewModel);
}

在我创建了一个房间并将这个房间添加到一个房子之后,我调用 Index 方法来查看一个房子的房间,列表是空的。

我可以就这段代码寻求帮助吗?

提前致谢

【问题讨论】:

    标签: c# list asp.net-mvc-4 visual-studio-2012 controller


    【解决方案1】:

    Entity Framework 和 LinqToSql 自动加载相关实体

    将它们设置为急切或延迟加载

    http://msdn.microsoft.com/en-us/data/jj574232.aspx(实体框架)

    In linq to sql how do I include the child entity with initial query?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多