0

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

2 Answers 2

2

Make this changes (you have to add info about the ForeignKey so EF can know how both tables are related):

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

public int UserId { get; set; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.