如何通过添加相关实体来创建视图?

时间:2017-11-08 07:45:11

标签: asp.net-mvc asp.net-core asp.net-core-mvc ef-core-2.0

我有ASP.Net Core MVC,EF Core 2.0的项目。有PersonPhone实体具有“一对多”关系,即每个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");}
}

0 个答案:

没有答案