ASP.NET MVC延迟加载不使用ICollection

时间:2017-01-29 13:40:09

标签: c# asp.net asp.net-mvc entity-framework

我创建了一个包含这两个模型的拍卖网站:

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; }

任何人都可以解释这种行为吗?

1 个答案:

答案 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; }
}