我正在使用代码优先方法。我有两个班级如下:
public class User
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int User_id { get; set; }
[Required]
[Column(Order = 1)]
[StringLength(50)]
[Display(Name = "Name")]
public string name { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode =true,DataFormatString ="{0:dd/MM/yyyy}")]
public DateTime? date_of_birth { get; set; }
[Required]
[Column(Order = 3)]
[StringLength(254)]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string email { get; set; }
public virtual ICollection<Product> products { get; set; }
}
public class Product
{
[Key]
[Required]
public int product_id { get; set; }
public int UserId { get; set; }
public virtual User user { get; set; }
[Required]
public string title { get; set; }
[Required]
public int type { get; set; }
[DataType(DataType.Date)]
public DateTime date_of_release { get; set; }
[Required]
public float price { get; set; }
}
我正在尝试添加新产品并将其与登录用户相关联。
这是我的视图模型:
public class AddProductViewModel
{
[Required]
public string title { get; set; }
[Required]
public int type { get; set; }
[DataType(DataType.Date)]
public DateTime date_of_release { get; set; }
[Required]
public float price { get; set; }
}
我无法弄清楚如何设置已登录用户ID的userId的值,因此我最终从数据库中查询了它并将其设置如下:
[HttpPost]
public ActionResult AddProduct(AddProductViewModel added)
{
if(ModelState.IsValid)
{
using (KitapTakasDB db = new KitapTakasDB())
{
string user_email = User.Identity.GetUserName();
Product product = new Product();
product.title = added.title;
product.price = added.price;
product.type = added.type ;
product.userId = db.User.Where(o => o.email ==
user_email).FirstOrDefault().user_id;
db.Product.Add(product);
db.SaveChanges(); //this is where the crash happens...
}
return RedirectToAction("Index", "Home");
}
return View();
}
提交表单时,我在db.SaveChanges()
网上遇到异常。
DbUpdateException:'更新条目时发生错误。有关详细信息,请参见内部异常。
内部例外:
datetime2数据类型到datetime数据类型的转换导致超出范围的值
我检查了空的DateTime,但它们不为空。
在向数据库添加新条目时设置外键的正确方法是什么?如果我的方法是正确的(我对此表示怀疑),该如何解决该错误?
谢谢
您似乎忘记了在此处添加日期。检查它是否不能为空或添加日期:
Product product = new Product();
product.title = added.title;
product.price = added.price;
product.type = added.type ;
product.date_of_release = added.date;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句