问题描述
我正在使用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);
}
谢谢
解决方法
如果您正在使用Entity Framework,我们需要配置多对多关系。 https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
之后,我们可以使用:customer.borrowedBooks.Add(book)
将其添加到多对多表中。