我有ASP.Net Core MVC,EF Core 2.0的项目。有Person
和Phone
实体具有“一对多”关系,即每个Person
实体可以包含许多电话或不包含任何电话。生成标准控制器时,还会生成视图。问题是,在创建Person
实体时,用户应该能够添加一个或多个电话。许多天谷歌没有给出任何东西,可能是因为我不知道如何在搜索中指定这一点。
如何创建能够动态添加相关实体的视图?换句话说,如何以编程方式创建和添加ICollection<Phone> Phone
集合新Phone
实体?
型号:
public partial class Person {
public Person() {
Phone = new HashSet<Phone>();
}
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Phone> Phone { get; set; }
}
}
public partial class Phone {
public int Id { get; set; }
public int Type { get; set; }
public int Number { get; set; }
public int? PersonId { get; set; }
public Person Person { get; set; }
}
public partial class ModelContext : DbContext {
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Person>(entity => {
entity.Property(e => e.Name).HasMaxLength(50).IsRequired();
});
modelBuilder.Entity<Phone>(entity => {
entity.HasOne(d => d.Person)
.WithMany(p => p.Phone)
.HasForeignKey(d => d.PersonId)
.HasConstraintName("FK_Phone_Person");
});
}
}
生成的视图:
@model xxx.Models.Person
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Person</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}