ASP.NET MVC,使用Entity Framework获取和显示数据

时间:2014-03-30 12:41:49

标签: entity-framework asp.net-mvc-4

我是ASP.NET MVC中的傻瓜,所以我遇到了很多问题。其中之一是: 如何获取所选用户的书籍列表(基于例如userId)并在视图中显示它们?

public class Book
{
    public Book()
    {
        this.States = new HashSet<State>();
        this.UserProfiles = new HashSet<UserProfile>();
    }

    public int BookId { get; set; }
    public string BookName { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public string PublicationLanguage { get; set; }

    public virtual ICollection<State> States { get; set; }
    public virtual ICollection<UserProfile> UserProfiles { get; set; }
}

public class UserProfile
{
    public UserProfile()
    {
        this.Books = new HashSet<Book>();
        this.webpages_Roles = new HashSet<webpages_Roles>();
    }

    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string UniversityName { get; set; }
    public string UniversityAddress { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
    public string PhoneNumber { get; set; }
    public Nullable<bool> Activated { get; set; }

    public virtual ICollection<Book> Books { get; set; }
    public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
}

书籍添加如下:

[HttpGet]
    public ActionResult AddBook()
    {
        Book book = new Book();
        return View(book);
    }

    [HttpPost]
    public ActionResult AddBook(Book book)
    {
        book.UserProfiles.Add(_bookService.GetUserById(WebSecurity.CurrentUserId)); // get currently logged in user
        _bookService.AddBook(book);
        return View("BookInfo", book);
    }

和_bookService.AddBook(书):

public void AddBook(Book book)
    {
        using (MyContext ctx = new MyContext())
        {
            ctx.Books.Add(book);
            ctx.SaveChanges();
        }
    }

问题可能微不足道,但我还在学习,我会很感激帮助

2 个答案:

答案 0 :(得分:1)

我建议你简化结构。只需将UserId属性添加到Book,然后从两个模型中删除虚拟集合。然后,使用LINQ,收集您想要的数据:

public List<Book> LoadBooksByUserId(int userId)
{
        using (MyContext ctx = new MyContext())
        {
            return ctx.Books.Where(e=>e.UserId == userId).ToList();
        }
}

您可以通过以下方式显示数据:Basic CRUD Functionality with the Entity Framework in ASP.NET MVC

答案 1 :(得分:0)

我认为您的图书 - 用户关系是多对多的,因为每个对象都有另一个对象的集合。如果是这种情况,您还应该将创建的书籍添加到用户的Books集合中。像这样:

_bookService.GetUserById(WebSecurity.CurrentUserId).Books.Add(book);
在AddBook操作中

。因此,您将参考用户的所有书籍。然后只需制作另一个方法/操作即可返回用户的书籍集合。例如:

public List<Book> LoadBooksByUser(int userId) 
{
    using (MyContext ctx = new MyContext())
    {
        return ctx.UserProfiles.Where(x => x.UserId = userId).Books.ToList();
    }
}