我创建了一个包含这两个模型的拍卖网站:
public class ItemModel
{
[Key]
public int ItemModelId { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime DateCreatedUtc { get; set; }
...
[ForeignKey("AcceptedBidModel")]
public int? AcceptedBidModelId { get; set; }
public virtual BidModel AcceptedBidModel { get; set; }
public virtual ICollection<BidModel> ItemBids { get; set; }
}
public class BidModel
{
[Key]
public int BidModelId { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime DateCreatedUtc { get; set; }
[Required]
[Range(1, Int32.MaxValue, ErrorMessage = "The bid must have a positive value")]
public int Bid { get; set; }
[ForeignKey("ItemModel")]
public int ItemModelId { get; set; }
public virtual ItemModel ItemModel { get; set; }
}
一切正常,ItemBids
填充了数据,但当我向BidModel
添加ItemModel
时(已接受的出价)ItemBids
变空了。
[ForeignKey("BidModel")]
public int? BidModelId { get; set; }
public virtual BidModel BidModel { get; set; }
任何人都可以解释这种行为吗?
答案 0 :(得分:0)
我通过移除已接受的出价(AcceptedBidModel
)解决了这个问题,并在BidModel
中创建了一个bool,表明出价是否为已接受的出价。
以下是新型号:
public class ItemModel
{
[Key]
public int ItemModelId { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime DateCreatedUtc { get; set; }
...
public virtual ICollection<BidModel> ItemBids { get; set; }
[NotMapped]
public BidModel AcceptedBid
{
get {
return ItemBids.Where(s => s.Accepted).SingleOrDefault();
}
set {}
}
}
public class BidModel
{
[Key]
public int BidModelId { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime DateCreatedUtc { get; set; }
public bool Accepted { get; set; }
[Required]
[Range(1, Int32.MaxValue, ErrorMessage = "The bid must have a positive value")]
public int Bid { get; set; }
[ForeignKey("ItemModel")]
public int ItemModelId { get; set; }
public virtual ItemModel ItemModel { get; set; }
}