This is ASP .net EF Core.
I have 2 classes. Nomination and User with one to many relationship.
Nomination will have foreign key pointing to User ID.
Classes:
public class Nomination
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int NominationId { get; set; }
public int NomineeUserId { get; set; }
public int NominationYear { get; set; }
public User Nominee { get; set; }
}
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailId { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
}
public class UserDto
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Context:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasKey(x => x.UserId);
modelBuilder.Entity<User>().Property(x => x.UserId).ValueGeneratedOnAdd();
modelBuilder.Entity<Nomination>().HasKey(x => x.NominationId);
modelBuilder.Entity<Nomination>().Property(x => x.NominationId).ValueGeneratedOnAdd();
modelBuilder.Entity<Nomination>().HasOne(x => x.Nominee).WithMany().HasForeignKey(x => x.NomineeUserId).OnDelete(DeleteBehavior.Restrict);
}
Controller GETALL:
public async Task<ActionResult<IEnumerable<Nomination>>> GetNomination()
{
return await _context.Nomination
.Include(n => n.NominationDetails)
.Include(n => n.Nominee)
.ToListAsync();
}
When I do GETALL for Namination, I am receiving the complete object of "Nominee"(User) including the password stuff. I need UserDTO instead of User. I do not need other properties of User
How should I change my code to accomplish this?