Home > Back-end >  How to use related value as select list DataTextField from model built with Dapper
How to use related value as select list DataTextField from model built with Dapper

Time:12-24

I am looking to populate a select list using values from 2 related tables but I get a Null Reference if using the related value as DataTextField.

Branch Model

public class BranchModel
{
    public int ContractorCode { get; set; }
    public int BranchNumber { get; set; }
    public string BranchName { get; set; }
    -- Excluded for brevity
}

Branch Assignment Model

public class BranchAssignmentModel
{
    public int Id { get; set; }
    public int Colleague { get; set; }
    public int Branch { get; set; }
    public DateTime Created { get; set; }
    public bool Active { get; set; }
    public DateTime LastModified { get; set; }
    public ColleagueModel? Col { get; set; }
    public BranchModel? Bra { get; set; }
}

Results are stored in List (colleagueId is a variable set earlier)

Assignments = new List<BranchAssignmentModel>();

            var basql = $@"SELECT ba.Colleague, ba.Branch, ba.Active, b.ContractorCode, b.BranchName 
                           FROM HR.BranchAssignment ba
                           JOIN HR.Branch b ON ba.Branch = b.ContractorCode
                           WHERE ba.Active = 1 AND ba.Colleague = {colleagueId}";

            using (var connection = new SqlConnection(_configuration.GetConnectionString("Default")))
            {
                var assignments = await connection.QueryAsync<BranchAssignmentModel, BranchModel, BranchAssignmentModel>(basql, (assignment,branch) =>
                {
                    assignment.Bra = branch;                    
                    return assignment;
                }, splitOn: "ContractorCode");
                foreach (var assignment in assignments)
                {
                    Assignments.Add(assignment);
                }
            }

Once run the list populates with the 5 expected results. When I create the select list with the following I get a Null Reference Exception.

SelectBranches = new SelectList(Assignments, 
   nameof(BranchAssignmentModel.Branch), nameof(BranchAssignmentModel.Bra.BranchName));

The image shows the relationship is there

Breakpoint

And if I don't use the related field the Select list shows fine i.e. just using the Branch as the DataTextField too

SelectBranches = new SelectList(Assignments, 
   nameof(BranchAssignmentModel.Branch), nameof(BranchAssignmentModel.Branch));

CodePudding user response:

If you use nameof(BranchAssignmentModel.Bra.BranchName), the DataTextField is BranchName.

You need specific the name like below:

SelectBranches = new SelectList(Assignments,
                nameof(BranchAssignmentModel.Branch), "Bra.BranchName");

enter image description here

  • Related