簡體   English   中英

從基本模型訪問數據庫

[英]Access to DB from base model

我有一個基本模型,如下所示,並且我正在使用該模型來獲取/設置每個模型的創建和修改日期。

 public class BaseModel 
    {
       [ForeignKey("CrUser")]
        public ApplicationUser UserCr { get; set; }
        public string CrUser { get; set; }

        public DateTime? MdDate { get; set; }

        [ForeignKey("MdUser")]
        public ApplicationUser UserMd { get; set; }

         public void LogBasic()
        {
            if (this.CrDate == null)
            {
                this.CrDate = System.DateTime.Now;
                this.CrUser = HttpContext.Current.User.Identity.GetUserId();
            }
            else
            {
                this.MdDate = System.DateTime.Now;
                this.MdUser = HttpContext.Current.User.Identity.GetUserId();
            }

        }
}

創建新條目時沒有問題,但是更新模型時,我無法設置MdUser。 我知道原因是,CrUser和CrDate為空,正如您在下面的方法中看到的那樣,它們沒有綁定。

這是我的一種編輯方法

    public ActionResult Edit([Bind(Include = "Id,Name,FullName,Address,TaxNumber,TaxOffice,Phone1,Phone2,Email,CompanyType")] CrmCompany crmcompany)
            {
                if (ModelState.IsValid)
                {
                    crmcompany.LogBasic();
                    db.Entry(crmcompany).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }

為了用我的方式解決問題,我需要傳遞CrDate和CrUser,或者我需要從數據庫獲取每種“編輯方法”的信息。

如何在我的LogBasic()方法中解決此問題。 如果我可以訪問DB並在LogBasic()方法中獲取Crdate和Cruser,則可以輕松解決問題,但是任何模型都可以調用LogBasic()方法。

無論如何,您都將必須使CrDate和CrUser進入模型創建或LogBasic函數。 如果您不更新,則它們將被清空,因為模型中未設置任何值。 我建議將它們存儲為隱藏字段,並按常規綁定它們。 這樣,您不必兩次訪問數據庫即可進行更新。

編輯:為了使這容易一些,您可以將此方法添加到您的BaseModel類。 它將輸出要綁定的隱藏字段。 我做了一些假設(例如UserIds都是正整數)。

public MvcHtmlString BaseModelHiddenFields()
{
    StringBuilder outputString = new StringBuilder();
    if(CrDate != null && CrDate.HasValue)
    {
        sb.AppendFormat("<input type=\"hidden\" name\="CrDate\" value=\"{0}\">", CrDate.Value);
    }
    if(CrUser > 0)
    {
        sb.AppendFormat("<input type=\"hidden\" name\="CrUser\" value=\"{0}\">", CrUser);
    }
    if(MdDate != null && MdDate.HasValue)
    {
        sb.AppendFormat("<input type=\"hidden\" name\="MdDate\" value=\"{0}\">", MdDate.Value);
    }
    if(MdUser > 0)
    {
        sb.AppendFormat("<input type=\"hidden\" name\="MdUser\" value=\"{0}\">", MdUser);
    }

    return MvcHtmlString.Create(sb.ToString());
}

暫無
暫無

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

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