日期:2014-05-17  浏览次数:20432 次

ASP.NET MVC3 在controller中如何为新建的记录新建关联记录?
本人新手,可能表述不太清楚,请大家原谅:

现在模型有:
C# code

public class CompanyInfo
    {
        [Key]
        [Column("id")]
        public int id { get; set; }

        public virtual List<CompanyInfoActHistory> CompanyInfoActHistorys { get; set; } //客户流水记录表
        

        //省略部分字段……
    }


以及:
C# code

    public class CompanyInfoActHistory
    {
        [Key]
        public int id { get; set; }

        [Column("CompanyId")]
        public int CompanyInfoId { get; set; }

        [Column("Actdate")]
        public DateTime Actdate { get; set; }

        [Column("UserId")]
        public int OperatorId { get; set; }

        [Column("ip")]
        public string IP { get; set; }

        [Column("Content")]
        public string Content { get; set; }

        public virtual CompanyInfo companyInfo { get; set; }

        public virtual Operator Operator { get; set; }
    }



个人想在创建公司记录的同时,创建日志流水,记录在表CompanyInfoActHistory中
在Create方法中按如下方法写,可是写不进去。
C# code

[HttpPost]
        public ActionResult Create(CompanyInfo companyInfo)
        {
            if (ModelState.IsValid)
            {
                CompanyInfoActHistory actHistory = new CompanyInfoActHistory()
                {
                    Actdate = System.DateTime.Now,
                    OperatorId = Convert.ToInt32(System.Web.HttpContext.Current.Request.Cookies["POM"]["Adminid"]),
                    IP = System.Web.HttpContext.Current.Request.UserHostAddress == null ? "" : System.Web.HttpContext.Current.Request.UserHostAddress,
                    Content = this.SetContent()
                };
                companyInfo.CompanyInfoActHistorys.Add(actHistory);

                db.CompanyInfo.Add(companyInfo);
                db.SaveChanges();
                return Content("成功新建记录", "text/html");
            }
            return Content("未成功新建记录", "text/html");
        }


求解释

------解决方案--------------------
把 actHistory.CompanyInfo = companyInfo 加上