简体   繁体   English

实体框架无法在 model 上添加新数据

[英]Entity Framework cannot add new data on model

i have a project where i work with a bookshop.我有一个与书店合作的项目。 And when a user buys a book, i want to add a record in the SoldBooks table with info about the book and the user.当用户购买书籍时,我想在 SoldBooks 表中添加一条记录,其中包含有关书籍和用户的信息。 But everything is fine with the add except when i want to add the User Id.但是除了我想添加用户 ID 之外,添加一切都很好。 Visual studio wont allow me to add an int "Cannot Implicitly convert type INT to models.User" Visual Studio 不允许我添加一个 int “无法将类型 INT 隐式转换为 models.User”

db.SoldBooks.Add(new SoldBook
{
 Title = book.Title,
 Author = book.Author,
 Price = book.Price,
 PurchaseDate = DateTime.Now,
 CategoryId = catid,
 User = 1                           
});
db.SaveChanges();

But when i check my database the field UserId says its an INT但是当我检查我的数据库时,字段 UserId 说它是一个 INT 在此处输入图像描述

What should i do to be able to add the User ID to a new record?我应该怎么做才能将用户 ID 添加到新记录? Thank you谢谢

Models/User.cs模型/用户.cs

class User
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        public string Password { get; set; }
        public DateTime LastLogin { get; set; }
        public DateTime SessionTimer { get; set; }
        public bool IsActive { get; set; }
        public bool IsAdmin { get; set; }
    }

Models/SoldBook.cs模型/SoldBook.cs

class SoldBook
    {
        [Key]
        public int Id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public int CategoryId { get; set; }
        public int Price { get; set; }
        public DateTime PurchaseDate { get; set; }
        public User User { get; set; }
    }

Make this changes (you have to add info about the ForeignKey so EF can know how both tables are related):进行此更改(您必须添加有关 ForeignKey 的信息,以便 EF 知道这两个表是如何相关的):

class SoldBook
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public int CategoryId { get; set; }
    public int Price { get; set; }
    public DateTime PurchaseDate { get; set; }
        
    public int IdUser { get; set; }
    [ForeignKey("IdUser")]
    public User User { get; set; }
}

and then add the record:然后添加记录:

db.SoldBooks.Add(new SoldBook
{
 Title = book.Title,
 Author = book.Author,
 Price = book.Price,
 PurchaseDate = DateTime.Now,
 CategoryId = catid,
 IdUser = 1                           
});
db.SaveChanges();

You should add additional UserId field to your SoldBook object and use it instead of User您应该将额外的 UserId 字段添加到您的 SoldBook object 并使用它而不是 User

public int UserId { get; set; }

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

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