Search code examples
c#entity-framework-6entity

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. But everything is fine with the add except when i want to add the User Id. Visual studio wont allow me to add an int "Cannot Implicitly convert type INT to 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 enter image description here

What should i do to be able to add the User ID to a new record? Thank you

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

Solution

  • You should add additional UserId field to your SoldBook object and use it instead of User

    public int UserId { get; set; }