我正在尝试更新用户,因此我可以添加书(书名和作者),方法是简单地发送带有书的HTTP req的ID,然后进行搜索。我没有得到理想的结果,但是,一切似乎都正常,除了您可以从下面的图片中看到的那样,我得到的是书中的所有内容(包括标题和作者)都为空值,而我搜索时不是如图2所示。
// Update user to include a rented book
public Users Update(Users user)
{
var usr = ctx.User
.Include(s => s.BooksRented)
.FirstOrDefault(b => b.Id == user.Id);
foreach (var bar in user.BooksRented)
{
var book = ctx.Book
.FirstOrDefault(b => b.Id == bar.Id);
//book.CurrentUser = usr;
book.UserId = user.Id;
usr.BooksRented.Add(book);
//ctx.Entry(book).State = EntityState.Modified;
}
//ctx.Entry(usr).State = EntityState.Modified;
ctx.SaveChanges();
return usr;
}
// Also tried this as suggested, it loops through by adding the user to
// books back and forth until it throws an error.
public Users Update(Users user)
{
Books book = new Books();
var r = ctx.User
.FirstOrDefault(b => b.Id == user.Id);
ctx.Entry(r).State = EntityState.Modified;
foreach (var bar in user.BooksRented)
{
book = ctx.Book
.FirstOrDefault(b => b.Id == bar.Id);
book.UserId = user.Id;
ctx.Entry(book).State = EntityState.Modified;
}
ctx.SaveChanges();
return r;
}
public class Books
{
public int Id { get; set; }
public string BookTitle { get; set; }
public string Author { get; set; }
public bool InRent { get; set; }
public Users CurrentUser { get; set; }
public DateTime Released { get; set; }
public DateTime RentedDate { get; set; }
public int UserId { get; set; }
}
public class Users
{
public int Id { get; set; }
public string Surname { get; set; }
public string Lastname { get; set; }
public List<Books> BooksRented { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Users>()
.HasMany(a => a.BooksRented)
.WithOne(r => r.CurrentUser)
.HasForeignKey(f => f.UserId);
}
答案 0 :(得分:1)
1)如果是EF,则需要在书本中使用外键UserId
2)您返回自己发送给该方法的用户
3)这是什么?您从数据库中保存了从数据库中收到的相同对象
Books book = new Books();
foreach (var bar in user.BooksRented)
{
book = ctx.Book
.FirstOrDefault(b => b.Id == bar.Id);
}
ctx.Entry(book).State = EntityState.Modified;
我想它可以用这样的东西:
1)在书籍中添加UserId
public class Books
{
public int Id { get; set; }
public string BookTitle { get; set; }
public string Author { get; set; }
public bool InRent { get; set; }
public Users CurrentUser { get; set; }
public DateTime Released { get; set; }
public DateTime RentedDate { get; set; }
public int UserId {get; set;]
}
2)将主代码更改为:
public Users RentBook(Users user)
{
var r = ctx.User
.FirstOrDefault(b => b.Id == user.Id);
ctx.Entry(user).State = EntityState.Modified;
foreach (var bar in user.BooksRented)
{
book = ctx.Book
.FirstOrDefault(b => b.Id == bar.Id);
book.UserId = user.Id;
ctx.Entry(book).State = EntityState.Modified;
}
ctx.SaveChanges();
return r.Include(x => x.BooksRented);
}
这也不是完全理想的,但我认为它会起作用。唯一不确定的是最后一行。