【问题标题】:Entity Framework cannot add new data on model实体框架无法在模型上添加新数据
【发布时间】:2021-03-19 08:04:36
【问题描述】:

我有一个与书店合作的项目。当用户购买书籍时,我想在 SoldBooks 表中添加一条记录,其中包含有关书籍和用户的信息。但是除了我想添加用户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 添加到新记录?谢谢

模型/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; }
    }

模型/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; }
    }

【问题讨论】:

    标签: c# entity-framework-6 entity


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      public int UserId { get; set; }
      

      【讨论】:

        猜你喜欢
        • 2022-10-14
        • 2018-10-03
        • 2016-03-19
        • 1970-01-01
        • 2020-10-23
        • 2017-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多