I am just starting with SQL and trying to get my first example working. I have two tables with a one-to-many relation:
public class Customer
{
public Guid Id { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
[JsonIgnore]
public virtual ICollection<Project> Projects { get; set; }
}
public class Project
{
public Guid Id { get; set; }
public string Name { get; set; }
public string ProjectType { get; set; }
public Guid CustomerId { get; set; }
public Customer Customer { get; set; }
}
Then I am executing following command through API ProjectsController
:
[HttpGet]
public async Task<IActionResult> Get()
{
System.Collections.Generic.List<Project> projects =
await _context.Projects.Include(d => d.Customer).ToListAsync();
return Ok(projects);
}
I am getting my
private IEnumerable<Project> ProjectsList { get; set; } = new List<Project>();
on the razor page, with
this.ProjectsList = await this.HttpClient.GetFromJsonAsync<IEnumerable<Project>>("api/Projects");
I have checked data structure of ProjectsList
with debugger and it looks fine.
However: the Razor page table (two columns "Project name" and "Customer name"):
<Table DataSource="ProjectsList" TItem="Project">
<Column TData="string"
Title="Name"
@bind-Field="context.Name"
SorterCompare="@((a,b)=> string.Compare(a,b))"
SortDirections="new[] { SortDirection.Descending }"
Filterable />
<Column TData="string"
@bind-Field="context.Customer.CompanyName"
SorterCompare="@((a,b)=> string.Compare(a,b))"
SortDirections="new[] { SortDirection.Descending }"
Filterable />
</Table>
I get an exception of object not set to instance of object. I guess this is because of context.Customer.CompanyName
where Customer
is not initialized?
First of all I have a question should I redo my Project
model and add there additional column of type string CompanyName
or there is some other way to get data displayed on razor page?
In case if... I should add additional column into Project.cs
how to query data using linq in there?
CodePudding user response:
First off, try the following, and if you get an error, post its text here:
public Customer Customer { get; set; } = new Customer {};