簡體   English   中英

ASP.net MVC / EF / C#不添加任何相關表記錄以在控制器中查詢

[英]ASP.net MVC/EF/C# add none related table records to query in controller

我正在嘗試從表位置添加職位名稱的記錄,以便用戶在編輯時為員工選擇職位。我最后一次嘗試是在公司模型中添加導航屬性(如字段)

public virtual ICollection<Position> Mpositions { get; set; }

但是到目前為止,我所得到的只是null ref異常或viewModel中沒有屬性“ PositionName”的每個視圖包的元素,每個人都不會費心地使用它,每個人都建議避免這樣做,所以也不要這樣做。

public ActionResult Edit([Bind(Include = "CompanyID,CompanyName,EntityForm,Address,Dissolute,CreationDate,FiscaleYear,Description")] Company company)
        {
            var GlbUpdate = db.Companies.Include(c => c.Members).Include(p => p.Mpositions);
            List<Company> mdlCompanies = new List<Company>();
            foreach (var item in GlbUpdate)
            {

                if ((item.Mpositions==null) || (item.Mpositions.Count() == 0))
                {
                    item.Mpositions = (ICollection<Position>)new SelectList(db.Positions.Except((IQueryable<Position>)db.Positions.Select(xk => xk.Members)), "PositionID", "PositionName");
                }
                mdlCompanies.Add(item);
//I tried first to edit the Mpositions property directly in gblUpdate
                //item.Mpositions = (IEnumerable<Position>)db.Positions.Select(p => new SelectListItem { Value = p.PositionID.ToString(), Text = p.PositionName}) ;
                //(ICollection<Position>)db.Positions.ToListAsync();
            }

以為我有這個

List<SelectListItem> mPositionNames = new List<SelectListItem>();
@*@this yields no results if I try gettign it from the compani record itself it gives a logic error where all id match all positionNames impossible to select an item and only positions already registered are available on the dropDownlist*@
@{foreach (var item in Model.Mpositions)
  {

    mPositionNames.Add(new SelectListItem() { Text = item.PositionName, Value = item.PositionID.ToString(), Selected = (false) ? true : false });
@*@selected attribute set to false not an issue, no data to select from :p so far*@
  }
}
@*@null exception(if i try to midify Mpositions directly in controler) here or empty list if modify it then put it with original query in a new list*@
<div class="SectionContainer R-sectionContainerData" id="MwrapperDataRight">
@Html.DropDownListFor(mpos => item.PositionID, (SelectList)Model.Mpositions)
</div>

我要做的就是拉職位表以創建一個dropdownList,以便用戶可以更改員工的職位,但是由於職位與員工而不是公司有1>很多關系,因此它不會自動受EF約束,我似乎也無法使用Include()添加它。

您對編輯職位的查詢很復雜。 此查詢只能編輯人的信息。 使用“編輯”操作來規范職位的編輯是不正確的。這再次成為“單一責任原則”。 在這種情況下使用ViewComponents 與人員信息分開加載位置。

我找到了一個合適的解決方案,該模型使用封裝其他實體的模型,然后使用Partialviews / RenderAction,以便每個部分處理一個實體/操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM