使用EF Core创建新记录会导致查找表插入新行

时间:2020-04-06 22:15:46

标签: c# razor ef-core-3.1

我正在使用带有脚手架的CRUD剃须刀页面的EF Core。 在我的父类中,我具有3个子表的属性及其ID的属性。 值正确显示在任何地方(查看详细信息,编辑,在网格中……没问题。) 在尝试创建新记录时,它们会正确显示(在下拉列表中)。

父母阶级

    public class Sample
    {
        public int Id {get; set;}

        public int CityId { get; set; }
        public City City { get; set; }

        public int StateId { get; set; }
        public State State { get; set; }

        public int CountyId { get; set; }
        public County County { get; set; }

        public DateTimeOffset DateReceived { get; set; } 
        public DateTimeOffset DateCreated { get; set; }
        public string DistributedTo { get; set; }
    }

城市阶层

    public class City
    {
        public int Id {get; set;}
        public string value {get; set;}
    }

其他两个查找都以相同的方式完成。

除了创建新记录时,所有其他东西都可以正常工作

  • EF Core将新记录插入子表(查找)中,
  • 新记录在VALUE属性中具有所选值的ID
  • 然后,将新子记录的ID插入父表(在CityIdStateIdCountyId中)
  • 代替下拉菜单中实际选择的ID。

因此,例如,如果我在State下拉列表中选择ID:1的值,而不是在Sample.StateId中输入1,则在State表中创建ID = 51,Vallue = 1的新记录然后将51放在Sample.StateId列中。

保存新记录的代码:

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Samples.Add(Sample);
        await _context.SaveChangesAsync();
        return RedirectToPage("./Index");
    }

我的Context类的相关部分:

    public DbSet<Sample> Samples { get; set; }
    public DbSet<City> Cities { get; set; }
    public DbSet<State> States { get; set; }
    public DbSet<County> Counties { get; set; }

0 个答案:

没有答案