我正在尝试建立一对多的关系。一家公司应该能够拥有多个董事会。我已经用这样的关系建立了我的模型。但是,我不确定如何调用正确的构造函数?当我使用 Create_Company 页面上的 EditForm 初始化对象时。
公司
public class Company
{
[Key]
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public DateTime Founded { get; set; }
public List<Board> Boards { get; set; }
public Company()
{
}
public Company(string name, DateTime founded)
{
Name = name;
Founded = founded;
Boards = new List<Board>();
}
}
我知道如何使用:
private Company Company { get; set; } = new Company("", new DateTime());
但不是我目前的做法:
创建_公司
@page "/create_company"
@inject NavigationManager Navigation
@inject HttpClient Http
<div>
<button class="btn btn-outline-secondary oi oi-arrow-left" @onclick="GoToReadCompany"></button>
<h3 class="text-center">Create Company</h3>
</div>
<hr />
<hr />
<EditForm Model="Company" OnValidSubmit="@HandleValidSubmit">
<ObjectGraphDataAnnotationsValidator />
<div class="form-group row">
<label for="Name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<InputText id="Name" class="form-control" placeholder="Name" @bind-Value="Company.Name" />
<ValidationMessage For="@(() => Company.Name)" />
</div>
</div>
<div class="form-group row">
<label for="CompanyFounded" class="col-sm-2 col-form-label">Founded</label>
<div class="col-sm-10">
<InputDate id="CompanyFounded" class="form-control" @bind-Value="Company.Founded" />
<ValidationMessage For="@(() => Company.Founded)" />
</div>
</div>
<hr />
<div class="row justify-content-md-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</EditForm>
@code {
private void GoToReadCompany()
{
Navigation.NavigateTo("/read_companies");
}
private Company Company { get; set; } = new Company();
private async void HandleValidSubmit()
{
try
{
var response = await Http.PostAsJsonAsync("api/Companies", Company);
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync();
Navigation.NavigateTo("/read_companies");
}
catch (Exception)
{
Console.WriteLine("Exception occurred for POST company");
}
}
}