0

我已经两次遇到这个问题了,我不太明白为什么。我通过发回视图模型在我的数据库中创建葡萄酒。该视图模型的 Wine 属性已正确填充,但是当我将更改保存在数据库中时,导航属性不会填充 - 就像我想的那样。我需要这个,因为我将这个 wine 对象传递给一个方法来将这些导航属性添加到我的搜索索引中。

我试图将数据库重新查询到一个新变量,但这也不起作用。我对此感到非常困惑-所以任何帮助都会很棒。我遇到了一个非常相似的问题,在这里没有收到任何答案。其他人通过在这里重新查询数据库解决了这个问题,但这对我不起作用。该模型在 GET 请求上很好地填充,但不是在帖子上。

控制器:

[HttpPost]
//[Authorize(Roles = "admin, producereditor")]
public ActionResult Create(NewWineViewModel nw)
{
    if (ModelState.IsValid)
    {
        nw.Wine.Active = nw.IsRequest ? false : true;
        //keep nullable for requests.
        nw.Wine.ImporterID = nw.Wine.ImporterID == 0 ? null : nw.Wine.ImporterID;
        nw.Wine.VarTypeID = nw.Wine.VarTypeID == 0 ? null : nw.Wine.VarTypeID;
        nw.Wine.OriginID = nw.Wine.OriginID == 0 ? null : nw.Wine.OriginID;
        nw.Wine.AppID = nw.Wine.AppID == 0 ? null : nw.Wine.AppID;
        nw.Wine.VintageID = nw.Wine.VintageID == 0 ? null : nw.Wine.VintageID;

        nw.Wine.CreatedBy = this.User.Identity.Name;
        nw.Wine.CreatedOn = DateTime.Now;
        db.Wines.Add(nw.Wine);

        db.SaveChanges();

        var wineToIndex = db.Wines.Find(nw.Wine.WineID);
       // nw.Wine.QRUrl = WineUtils.MakeQRCode(nw.Wine);
        //db.SaveChanges();


        //Lucene.LuceneSearch.AddUpdateLuceneIndex(db.Wines.Find(nw.Wine.WineID));


        if (nw.IsRequest)
        {
            nw.VOAVIRequest.WineID = nw.Wine.WineID;
            nw.VOAVIRequest.CreatedBy = User.Identity.Name;
            nw.VOAVIRequest.CreatedOn = DateTime.Now;
            db.VOAVIRequests.Add(nw.VOAVIRequest);
            db.SaveChanges();

            return RedirectToAction("Requested");

            //redirect to "Request Submitted" page for new wines
        }

        return RedirectToAction("Details", new { id = nw.Wine.WineID });
    }

    ViewBag.VarTypeID = new SelectList(db.VarTypes, "VarTypeID", "Name").Default("Select a Varietal/Type", nw.Wine.VarTypeID.ToString());
    ViewBag.OriginID = new SelectList(db.Origins, "OriginID", "Name").Default("Select an Origin", nw.Wine.OriginID.ToString());
    ViewBag.AppID = new SelectList(db.Apps, "AppID", "Name").Default("Select an Appellation", nw.Wine.AppID.ToString());
    ViewBag.VintageID = new SelectList(db.Vintages, "VintageID", "Name").Default("Select a Vintage", nw.Wine.VintageID.ToString());
    ViewBag.ImporterID = new SelectList(db.Importers, "ImporterID", "Name").Default("Select an Importer", nw.Wine.ImporterID.ToString());
    if (User.IsInRole("producer"))
    {
        Producer currentProd = db.ProducerUsers.Find(Membership.GetUser().ProviderUserKey).Producer;
        ViewBag.ProducerID = currentProd.ProducerID;
        ViewBag.ProducerName = currentProd.Name;
    }
    else
    {
        ViewBag.ProducerSelect = new SelectList(db.Producers, "ProducerID", "Name", nw.Wine.ProducerID);
    }
    return View(nw);
}

视图模型:

public class NewWineViewModel
{

    public Wine Wine { get; set; }
    public VOAVIRequest VOAVIRequest { get; set; }
    public bool IsRequest { get; set; }

    public SelectList VarTypes { get; set; }
    public SelectList Origins { get; set; }
    public SelectList Apps { get; set; }
    public SelectList Vintages { get; set; }
    public SelectList Importers { get; set; }

    public NewWineViewModel()
    {
        this.Wine = new Wine();
    }

}

模型:

public class Wine :Updater
{
    public int WineID { get; set; }
    //public int WineTypeID { get; set; }
    [Display(Name = "Varietal/Type")]
    public int? VarTypeID { get; set; }
    [Display(Name = "Origin")]
    public int? OriginID { get; set; }
    [Display(Name = "Appellation")]
    public int? AppID { get; set; }
    [Display(Name = "Vintage")]
    public int? VintageID { get; set; }
    [Display(Name = "Importer")]
    public int? ImporterID { get; set; }
    public int ProducerID { get; set; }
    public string Designate { get; set; }
    [Display(Name = "Drink Window")]
    public string DrinkWindow { get; set; }
    public string Body { get; set; }
    public string SKU { get; set; }
    [Display(Name = "Varietal Makeup")]
    public string VarietalMakeup { get; set; }
    [Display(Name = "Case Production")]
    public string CaseProduction { get; set; }
    [Display(Name = "Alcohol Content")]
    public double? AlcoholContent { get; set; }
    public string Winemaker { get; set; }
    [Display(Name = "Consulting Winemaker")]
    public string ConsultWinemaker { get; set; }
    public bool Sustainable { get; set; }
    public bool Kosher { get; set; }
    public bool Organic { get; set; }
    public bool Biodynamic { get; set; }
    public bool SalmonSafe { get; set; }
    public Boolean Active { get; set; }
    [Display(Name = "ResidualSugar")]
    public double? RS { get; set; }
    public double? pH { get; set; }
    public string QRUrl { get; set; }


    public virtual WineType WineType { get; set; }

    public virtual VarType VarType { get; set; }
    public virtual Origin Origin { get; set; }
    public virtual App App { get; set; }
    public virtual Vintage Vintage { get; set; }
    public virtual Importer Importer { get; set; }
    public virtual Producer Producer { get; set; }

    [JsonIgnore]
    public virtual ICollection<POS> POSs { get; set; }
    [JsonIgnore]
    public virtual ICollection<Review> Reviews { get; set; }
    [JsonIgnore]
    public virtual ICollection<Doc> Docs { get; set; }

    [JsonIgnore]
    public IEnumerable<SelectListItem> BodyList { get; set; }
4

1 回答 1

3

该视图模型的 Wine 属性已正确填充,但是当我将更改保存在数据库中时,导航属性不会填充 - 就像我想的那样。

将更改保存到数据库永远不会从数据库加载数据,因此无法填充导航属性。在这种特定情况下,您所期望的是延迟加载将在您访问它们时立即传播导航属性(virtual在您的模型中)。这实际上是对每个导航属性的单独查询。

现在,问题是延迟加载无法在您的 POST 操作中工作,因为模型绑定器已经实例化了nw.Wine实体。但是模型绑定器(它对实体框架一无所知)不会为 Wine 实体创建延迟加载代理对象,而只是使用new(或者可能是反射 API 的一些实例化)。延迟加载代理需要延迟加载工作。

如果您要nw.Wine手动创建实体,则可以使用...创建延迟加载代理

nw.Wine = db.Wines.Create();

...而不是使用nw.Wine = new Wine();. 然后,您的代码将按预期工作,并且在您将实体附加/添加到 EF 上下文后,延迟加载将填充导航属性。

您在评论中提出的解决方案...

nw.Wine.Producer = db.Producers.Find(nw.Wine.ProducerID)

...(对于其他导航属性也是如此)在我看来是正确的方法。或者,您可以使用显式加载:

db.Entry(nw.Wine).Reference(w => w.Producer).Load();

但是所有这三种情况 - 延迟加载(如果可以的话),使用Find或使用显式加载 - 将执行相同的数据库查询。因此,在性能方面没有区别。

在您的 GET 操作中延迟加载是有效的,因为 - 我猜 - 您正在从数据库中加载 wine 实体......

var wine = db.Wines.Find(id); // or maybe `Single` or `First`, etc.

...并从数据库中加载实体会创建一个延迟加载代理。

于 2012-08-16T21:00:39.233 回答