Is it possible to modify existing value of foreign key with EF core?

Viewed 110

I have two entities which have one to one relationship:

public class User
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string CarId { get; set; }
    public Car Car{ get; set; }
}

and

 public class Car
 {
    [Key]
    public int Id { get; set; }

    [Required]
    public string PlateNumber{ get; set; }

    [Required]
    public string Description { get; set; }

    public int UserId { get; set; }
    public User User { get; set; }
}

Let say I have User with Id 1 which is related to Car with Id 5 (I have 5 cars already inserted into the table "Cars"). Is it possible to modify existing relation of User to Car(1->5) with another car(car with Id 2 for instance and become 1->2) using EF Core and if yes can you give me an example?

1 Answers

you data schema is not valid and will be compilled. You can not have UserId in Car class and in the same time CarId in User. So you have to select something one. IMHO it is better to keep UserId in Car, but remove CarId from User. You can keep one Car property in user if you use Net 5+, otherwise you will have to assign List

public class User
{
    [Key]
    public int Id { get; set; }

       .....

     public virtual Car Car { get; set; }

     //but it is much better
      public virtual List<Car> Cars { get; set; }
  
}


 public class Car
 {
    [Key]
    public int Id { get; set; }

    ....

    public int UserId { get; set; }
    public virtual User User { get; set; }
}
Related