MVC5如何将对象与当前用户连接?

时间:2020-08-29 02:35:44

标签: c# asp.net-mvc-5

我正在使用MVC制作Library,而我几乎完成了全部工作。我最后要做的就是让客户借书。为了做到这一点,我想找出如何将当前登录用户与某些书联系起来的方法。我希望用户能够单击“借书”,并且他将有可用的书。您能给我解释一下如何将这两个连接起来吗?

家庭控制器:

public ActionResult Borrow(string CustomerId, string Id)
{
    Customer customer = customerContext.Find(CustomerId);
    Book book = context.Find(Id);

    if (customer != null && book != null)
    {
        customer.borrowedBooks.Add(book);

        context.Insert(book);
        context.Commit();

        return RedirectToAction("Index", "Manage");
    }
    else
    {
        return HttpNotFound();
    }
}

客户类别:

public class Customer : BaseEntity
{
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string PostCode { get; set; }
    public List<Book> borrowedBooks { get; set; }
    public Customer() {

    }
}

图书班:

public class Book : BaseEntity
{
    [StringLength(30)]
    [DisplayName("Book Title")]
    public String Title { get; set; }
    [DisplayName("Writer First Name")]
    public String WriterFirstName { get; set; }
    [DisplayName("Writer Last Name")]
    public String WriterLastName { get; set; }
    [DisplayName("Released")]
    public DateTime ReleaseDate { get; set; }
    [DisplayName("Publisher")]
    public String Publisher { get; set; }
    [DisplayName("Number of Books")]
    public int NumberOfBooks { get; set; }
    public String Genre { get; set; }
    public String Format { get; set; }
    public String Description { get; set; }
    public String Image { get; set; }
    public static int Count { get; set; }

    public Book()
    {
        
    }
}

IRepository:

public interface IRepository<T> where T : BaseEntity
{
    IQueryable<T> Collection();
    void Commit();
    void Delete(string Id);
    T Find(string Id);
    void Insert(T t);
    void Update(T t);
}

谢谢

1 个答案:

答案 0 :(得分:0)

如果您正在使用Entity Framework,我们需要配置多对多关系。 https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

之后,我们可以使用:customer.borrowedBooks.Add(book)将其添加到多对多表中。