简体   繁体   English

在 Asp.Net MVC 中将数据插入数据库时如何设置外键值

[英]How to set value of foreign key when inserting data into database in Asp.Net MVC

I am using code first approach.我正在使用代码优先方法。 I have two classes as the following:我有两个类如下:

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; }
}

I'm trying to add new Product and associate it with the logged user.我正在尝试添加新产品并将其与登录用户相关联。

This is my view model:这是我的观点 model:

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; }
}

I could not figure out how to set the value of the userId which is the logged in user id so i ended up querying it from the database and setting it as following:我不知道如何设置作为登录用户 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();
}

When submitting the form, I get an exception on db.SaveChanges() line.提交表单时,我在db.SaveChanges()行上遇到异常。

DbUpdateException: 'An error occurred while updating the entries. DbUpdateException: '更新条目时发生错误。 See the inner exception for details.'有关详细信息,请参阅内部异常。

Inner exception:内部异常:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围

I checked for null DateTime but they were not null.我检查了 null 日期时间,但它们不是 null。

What is the proper approach of setting the foreign key when adding new entry to the database?向数据库添加新条目时设置外键的正确方法是什么? And if my approach is correct (I doubt it), how can I fix this error?如果我的方法是正确的(我对此表示怀疑),我该如何解决这个错误?

Thanks谢谢

It seems you forgot to add the date here.您似乎忘记在此处添加日期。 Check if it not nullable or add the date:检查它是否不可为空或添加日期:

Product product = new Product();
product.title = added.title;
product.price = added.price;
product.type = added.type ;

product.date_of_release = added.date;

If you have already verified that the date is not null and that is not the problem, you are probably passing a date that is out of bounds between SqlDateTime.MinValue() and SqlDateTime.MaxValue() .如果您已经验证日期不是 null 并且这不是问题,那么您可能传递的日期超出了SqlDateTime.MinValue()SqlDateTime.MaxValue()之间的界限。

SQL DateMin: (January 1, 1753) SQL 日期:(1753 年 1 月 1 日)

SQL DateMax: (December 31, 9999) SQL DateMax:(9999 年 12 月 31 日)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM