如何从controllerp分配pk值

时间:2018-01-15 06:00:49

标签: entity-framework asp.net-mvc-5

ArticleIDX是主键。  我想将此主键分配给Family。  但是,主键似乎未分配Family值,因为create方法已执行并递增。 在这种情况下我该怎么做?

[HttpPost]
    public ActionResult Create(Articles article)
    {
        try
        {
            **article.Family = article.ArticleIDX;**
            article.Parent = 0;                 
            article.Depth = 0;                  
            article.Indent = 0;                 
            article.ModifyDate = DateTime.Now;
            article.ModifyMemberID = User.Identity.Name;

            db.Articles.Add(article);
            db.SaveChanges();

            }
            ViewBag.Result = "OK";
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Board");
            Debug.WriteLine(ex.ToString());
            ViewBag.Result = "FAIL";
        }
        return View(article);
    }


public partial class Articles
{
    [Key]
    public int ArticleIDX { get; set; }

    public int? Family { get; set; }

    public int? Depth { get; set; }

    public int? Indent { get; set; }

    public int? Parent { get; set; }

    [StringLength(200)]
    public string Title { get; set; }

    [Column(TypeName = "text")]
    public string Contents { get; set; }

    [StringLength(50)]
    public string Category { get; set; }

    [StringLength(20)]
    public string ModifyMemberID { get; set; }

    public DateTime? ModifyDate { get; set; }

    public virtual Members Members { get; set; }

}

1 个答案:

答案 0 :(得分:0)

因为插入前未生成主键。您应该先插入行,然后在之后分配生成的主键。

article.Family = 0;
article.Parent = 0;
article.Depth = 0;
article.Indent = 0;
article.ModifyDate = DateTime.Now;
article.ModifyMemberID = User.Identity.Name;

db.Articles.Add(article);
db.SaveChanges();
article.Family = article.ArticleIDX;//Update the Family after primary key generated
db.SaveChanges();