Entity Framework 无法在模型上添加新数据

Entity Framework cannot add new data on model

我有一个与书店合作的项目。当用户购买一本书时,我想在 SoldBooks table 中添加一条记录,其中包含有关该书和用户的信息。但是添加一切都很好,除非我想添加用户 ID。 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();

但是当我检查我的数据库时,字段 UserId 说它是一个 INT

我应该怎么做才能将用户 ID 添加到新记录中?谢谢

Models/User.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

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

您应该向您的 SoldBook 对象添加额外的 UserId 字段并使用它来代替 User

public int UserId { get; set; }

进行此更改(您必须添加有关 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; }
}

然后添加记录:

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