I am trying to enter the last generated id of the user into another table column. I tried the following things.
Controller:
public void AddCartDetails(int id, int num)
{
Cart cart = new()
{
CartNumber = num,
User = id,
CartQty = 0,
CartTotal = 0
};
_repository.AddCart(cart);
if (_repository.SaveAll())
{
// Do something
}
}
When I tried this I am getting an error
Can't implicitly convert int to model type
This happens near the User = id
line of code. This happens because I am trying to map an int to a model. I am missing something really basic here but I cannot figure this one out. Any help is appreciated.
User
class:
public class User
{
public int UserId { get; set; }
public int UserNumber { get; set; }
public string UserFName { get; set; }
public string UserLName { get; set; }
public string UserEmail { get; set; }
public string UserPhoneNumber { get; set; }
public string UserRole { get; set; }
}
Cart
class:
public class Cart
{
public int CartId { get; set; }
public int CartNumber { get; set; }
public int CartQty { get; set; }
public decimal CartTotal { get; set; }
public ICollection<CartItems> Items { get; set; }
public User User { get; set; }
}
CodePudding user response:
You are trying to set the User property to int, but in Cart class User is the User object.
Cart cart = new()
{
CartNumber = num,
User = id, // here id is int type
CartQty = 0,
CartTotal = 0
};
Have a look at Cart class:
public class Cart
{
public int CartId { get; set; }
public int CartNumber { get; set; }
public int CartQty { get; set; }
public decimal CartTotal { get; set; }
public ICollection<CartItems> Items { get; set; }
public User User { get; set; } // here User is User type
}
You should change User to int type or add new property e.g. UserId depending on your needs.
CodePudding user response:
Because User have type of "User" and not integer, you cannot assign in to it. You can either create new user with id of your input:
var user= new User(){ UserId=id };
Cart cart = new()
{
CartNumber = num,
User = user ,
CartQty = 0,
CartTotal = 0
};
Or you can look for this post: