更新& # 39;父母# 39;实体,而不是创建它

本文关键字:创建 实体 父母 更新 | 更新日期: 2023-09-27 18:05:17

我列出了一系列项目,我想要实现一个选项,当你点击它,它添加一个子对象的实体,让我解释一下:

    public class SupportItem
   {
    [Display(Name = "Categoría")]
    [ConcurrencyCheck, Required]
    public string Type { get; set; }
    [Key, HiddenInput(DisplayValue = false)]       
    public int SupportItemId { get; set; }
    [Display(Name = "Nombre")]
    [ConcurrencyCheck,Required]
    public string Name { get; set; }
    [ConcurrencyCheck]
    [Display(Name = "Descripción Corta")]
    [DataType(DataType.MultilineText)]
    [Required]
    public string Description { get; set; }
     [HiddenInput(DisplayValue = false)]
    public virtual SupportItem Father { get; set; }
    [Display(Name = "Descripción detallada")]
    [DataType(DataType.MultilineText)]
    [Required]
    public string LongDescription { get; set; }
    [HiddenInput(DisplayValue = false)]
    public bool Children { get; set; }
}

现在你可以看到,这个实体有一个类型为supportitem的父。现在我要做的是列出它们并添加一个选项,这将使您可以轻松地为所选项目添加子元素,这是视图定义:

    @model IEnumerable<Domain.Entities.SupportItem>
    @{
        ViewBag.Title = "IndexSupportItems";
        Layout = "~/Views/Shared/_AdminLayout.cshtml";
    }
    <h2>Index Support Items</h2>
    <p>
    @Html.ActionLink("Crear nuevo item principal", "Create")
    </p>
    <table class="Grid">
    <tr>
    <th>
        Tipo
    </th>
    <th>
        Nombre
    </th>
    <th>
        Descripción
    </th>
    <th> 
        Acciones
    </th>                
    </tr>
     @foreach (var item in Model) 
    {
    <tr>
    <td>@item.Type</td>
    @if(item.Children)
    {
    <td>@Html.ActionLink(item.Name,"ListChildren", new{item.SupportItemId})</td>
    }
    else
    {<td>@item.Name</td>
    }
    <td>@item.Description</td>
        <td>
       @Html.ActionLink("Delete","DeleteSupportItem", new{item.Father.SupportItemId})<br />
        @Html.ActionLink("Add subitem sub-item","AddSubitem", new{item.SupportItemId})<br />
        @Html.ActionLink("Edit","EditSupportItem", new{item.SupportItemId})    
    </td>
</tr>
    }
    </table>
现在可以看到,执行此操作的操作链接指向一个名为AddSubitem的方法,其实现如下:
    public ViewResult AddSubitem(int supportItemId)
    {
        SupportItem child = new SupportItem() { Father = repo.GetSupportItemFromId(supportItemId) };
        return View(child);
    }

正如您所看到的,我收到一个supporttitemid,这是来自父实体(我想要添加新子实体的那个)的id,在我的数据库上下文中找到它,并创建新对象并指向我刚刚找到的父亲对象。之后,它返回的视图是这样的:

    @model Domain.Entities.SupportItem
    @{
        ViewBag.Title = "AddSubitem";
    }
    <h2>AddSubitem</h2>
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>Support Item</legend>
            <div class="editor-label">
        @Html.LabelFor(model => model.Type)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Type)
        @Html.ValidationMessageFor(model => model.Type)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Description)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Description)
        @Html.ValidationMessageFor(model => model.Description)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.LongDescription)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LongDescription)
        @Html.ValidationMessageFor(model => model.LongDescription)
    </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

在这个视图中,用户将设置一些变量,如名称和描述,然后提交对象,以便我可以将其持久化到数据库,问题是我从这个视图中获得的对象有它的父亲id作为它自己的id,父亲属性是空的,因此我最终更新了父亲对象,我想用这个方法添加一个子对象:

public bool SaveSupportItem(supporttitem){

        if (supportItem.SupportItemId == 0)
        {
            context.SupportItems.Add(supportItem);
            supportItem.Father.Children = true;
            retorno = true;
        }
        else
        {
            SupportItem itemDB = context.SupportItems.Find(supportItem.SupportItemId);
            if (itemDB != null)
            {
                itemDB.Name = supportItem.Name;
                itemDB.Type = supportItem.Type;
                itemDB.LongDescription = supportItem.LongDescription;
                itemDB.Description = supportItem.Description;
                retorno = true;
            }
        }
        context.SaveChanges();
        return retorno;
    }

我在这里做错了什么?为什么我不能创建一个新对象?

感谢您花时间阅读这篇文章,任何帮助都将非常感激!

更新& # 39;父母# 39;实体,而不是创建它

试试这个:

将此添加到您的supporttitem类

public class SupportItem
{
  [Key]
  [HiddenInput(DisplayValue = false)]
  [ForeignKey("Father"), DatabaseGenerated(DatabaseGeneratedOption.None)]       
  public int SupportItemId { get; set; }
  public virtual Father Father { get; set; }
  ...................
  ...................
}

然后改变:

@Html.ActionLink("Add subitem sub-item","AddSubitem", new{item.SupportItemId})<br />

@Html.ActionLink("Add subitem sub-item","AddSubitem", "Controller Name here" new{SupportItemId = @Model.FatherId})<br />

还因为我们这里需要父亲id new{SupportItemId = @Model.FatherId},所以ActionLink需要在父亲视图中,例如在父亲详细信息中,只有单亲父亲是当前的,或者当您必须将supportItem与特定的父亲关联时。

您的控制器可能看起来像这样,假设您正在使用ViewModel:

    [HttpGet]
    public ActionResult CreateSuppo(int supportItemId)
    {
        var model = new CreateSupportItemViewModel ();
        model.SupportItemId= supportItemId;
        return View(model);
    }
    [HttpPost]
    public ActionResult Create(CreateSupportItemViewModel viewModel)
    {
        if(ModelState.IsValid)
        {
            var father= db.Fathers.Single(f => f.FatherId == viewModel.SupportItemId);
            var supportItem= new SupportItem();
            supportItem.Name = viewModel.Name;
            ....................
            .................
            father.SupportItems.Add(supportItem);
            db.SaveChanges();               
        }
        return View(viewModel);
    }