【问题标题】:Navigation Properties on Post ActionPost Action 的导航属性
【发布时间】:2013-09-10 21:05:46
【问题描述】:

我需要在后期编辑操作中访问导航属性,但我目前的做法看起来并不是最好的选择,因为我调用了数据库并“重新更新”了模型。有没有更好的解决方案?

public class Foo
{
    public int Id { get; set; }
    public string SomeProp { get; set; }
}

public class Bar
{
    public int Id { get; set; }
    public int FooId { get; set; }
    public Foo Foo { get; set; }
}

[HttpPost]
public ActionResult Edit(Bar bar)
{
    // Here bar.FooId is set but bar.Foo is null as bar is not a Dynamic Proxy.

    ...

    bar = db.Bar.Find(bar.id);
    TryUpdateModel(bar);

    return View(bar);  // Here bar.Foo is set.
}

我发现的另一种方法是:

db.Bar.Attach(bar);
db.Entity<Bar>(bar).Reference(b => b.Foo).Load();

但这需要我引用我需要的所有导航属性。

【问题讨论】:

    标签: asp.net-mvc entity-framework navigation-properties dynamic-proxy


    【解决方案1】:

    我不能 100% 确定这是否是正确或最佳的方法,但是,在您处理帖子的 UI 表单中,UI 元素需要绑定到导航属性,或者您也可以传递它们如果它们没有被修改,则作为隐藏字段

    <!-- example of hidden properties -->
    @Html.HiddenFor(x=>x.Foo.FooId)
    
    <!-- exampld of editable UI element mapped to navigation property's someprop property -->
    @Html.TextBoxFor(x=>x.Foo.SomeProp)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-14
      相关资源
      最近更新 更多