I have a User
class with a one-many relationship with two other classes, InterestRate
and Loan
respectively. I would like for a specific loan
to inherit the initial interestRate
value of a user
when a new loan
is created but retain that value even if the user's
initial interestRate
value changes.
When I try assigning the value of the user's interestRate to a new loan like so,
public async Task<LoanRequest> AddLoanRequest(LoanRequestForCreationDto field)
{
var data = new LoanRequest
{
LoanAmount = field.LoanAmount,
LoanTenure = field.LoanTenure,
AppUserId = field.AppUserId,
InterestRate = AppUser.InterestRate
};
await context.LoanRequests.AddAsync(data);
await context.SaveChangesAsync();
return data;
}
I get the object reference error.
Although I am able to update the user's interest rate using the following code:
public async Task<AppUser> UpdateUserInterestRate(UserInterestForUpdateDto field)
{
var dataFromRepo = await context.Users.Include(x => x.PreviousInterestRates).FirstOrDefaultAsync(i => i.Id == field.AppUserId);
var data = new InterestRate
{
AppUserId = field.AppUserId,
Rate = dataFromRepo.InterestRate
};
await context.InterestRates.AddAsync(data);
dataFromRepo.InterestRate = field.NewInterestRates;
await context.SaveChangesAsync();
return dataFromRepo;
}
The interestRate on the loan is not affected. I am aware that I could hardcode the desired interestRate of the user to the loan using
InterestRate = field.InterestRate
but I would like for the system to be dynamic.
CodePudding user response:
That's because the AppUser object is null and you are getting error that of "object reference" error when you try to access its InterestRate. To prevent this, you can first fetch the user object from the database, and then check if it is null. If it is null, you can either return null or throw an exception indicating that such a user doesn't exist.
Although try this code:
public async Task<LoanRequest> AddLoanRequest(LoanRequestForCreationDto field)
{
var user = await context.Users.FindAsync(field.AppUserId);
// If the user doesn't exist, return null or throw an exception
if (user == null)
{
// Option 1: Return null
return null;
// Option 2: Throw an exception
// throw new Exception("User not found");
}
var data = new LoanRequest
{
LoanAmount = field.LoanAmount,
LoanTenure = field.LoanTenure,
AppUserId = field.AppUserId,
InterestRate = user.InterestRate
};
await context.LoanRequests.AddAsync(data);
await context.SaveChangesAsync();
return data;
}