c# MVC实体框架不更新对象的List属性

本文关键字:对象 List 属性 更新 MVC 实体 框架 | 更新日期: 2023-09-27 18:03:10

我正在制作拍卖应用程序。目前我正在招标系统工作。我的Auction模型包括:

public class Auctions
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    (...) some more fields like title, description etc(...)
    public List<Bid> bids = new List<Bid>(); // a list of bids from the users
}
public class Bid
{
    public string bidAuthor { get; set; }
    public decimal bid { get; set; }
    public DateTime bidDate { get; set; }
}

在视图中,我有一个发送投标的表单:

@model BiddingViewModel 
(...)info stuff about the auction(...)
@using (Html.BeginForm("CreateBid", "Auction", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model=>model.auctionToSend.ID)
    @Html.EditorFor(model => model.bid)
    <input type="submit" value="Send a bid" />
}
然后,我的控制器:
    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> CreateBid(BiddingViewModel bvm)
    {
        var user = await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
        var tmp = _context.Auctions.FirstOrDefault(i => i.ID == bvm.auctionToSend.ID);
        Bid newBid = new Bid()
        {
            bid = decimal.Parse(bvm.bid.ToString()),
            bidAuthor = user.Email,
            bidDate = DateTime.Now
        };
        tmp.bids.Add(newBid);
        _context.Entry(tmp).State = Microsoft.Data.Entity.EntityState.Modified;
        _context.SaveChanges();
        return RedirectToAction("AuctionList", "Auction");
    }

不幸的是,这似乎没有更新我的bids列在我的数据库(这是类型VARBINARY(MAX))。我做错了什么?

c# MVC实体框架不更新对象的List属性

我将尽可能地向未来的用户解释这个问题:问题是我试图将List添加为表的一列。我应该做的是为投标添加一个新表,链接在ApplicationDbContext:

public DbSet<Auctions> Auctions { get; set; }
public DbSet<Bid> Bids { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Auctions>()
   .HasOne(p => p.Signup)
   .WithMany(b => b.Auction);
   modelBuilder.Entity<Bid>()
   .HasOne(p => p.Auction)
   .WithMany(b => b.bids);
   base.OnModelCreating(modelBuilder);
}

其余部分在Stephen Muecke的评论中解释

相关文章: