C# EF是否未将当前用户ID和日期保存到数据库?
有人能检查一下下面的代码,告诉我为什么UserId和Date字段没有填充吗C# EF是否未将当前用户ID和日期保存到数据库?,c#,entity-framework,asp.net-mvc-5,C#,Entity Framework,Asp.net Mvc 5,有人能检查一下下面的代码,告诉我为什么UserId和Date字段没有填充吗 [HttpPost] [ValidateAntiForgeryToken] public ActionResult RecordCard(WeightViewModel vModel) { Weight Model = vModel.Weight; if (ModelState.IsValid) { using (WebApplication1Entities db = new W
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(WeightViewModel vModel)
{
Weight Model = vModel.Weight;
if (ModelState.IsValid)
{
using (WebApplication1Entities db = new WebApplication1Entities())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
发布后,表Weight有一个新记录,其中包含Stone和Pound值,但UserId和Date为Null
我已将以下重量等级包含在数据参考中:
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
公共部分类权重
{
公共int Id{get;set;}
公共字符串用户标识{get;set;}
公共可为空的Stone{get;set;}
公共可空Pound{get;set;}
公共可空日期{get;set;}
}
任何帮助都将不胜感激:-)因为您这样做:
db.Weights.Add(Model);
与此相反:
db.Weights.Add(weight);
这是一个非常好的理由,让ViewModel
类不是您的DomainModel
类。如果ViewModel
是不同的类型
,Add
到数据库上下文将失败,并出现编译错误