实体框架dbcontext中的一对多冲突

时间:2020-02-10 13:31:16

标签: asp.net asp.net-mvc entity-framework asp.net-core

我在数据库中有两个表,如下所示

Table Beneficiaries contains ID, Name, and Object of table BeneficiariesGroup as bgroup
Tabel BeneficiariesGroup contains ID, Name 

因此1个受益人有1个组,而一个组包含多个受益人 声明受益人时,如何修改OnModelCreating以能够读取组的名称

我的dbcontext类如下

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {            
    }

    public DbSet<Beneficiaries> Beneficiaries { get; set; }
    public DbSet<BeneficiariesGroup> BeneficiariesGroup { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<Beneficiaries>().HasOne<BeneficiariesGroup>(a => a.bgroup).WithMany(b=>b.beneficiary);                           
    }
}

实体:

 public class Beneficiaries
{
    public int ID { get; set; }
    public string CUID { get; set; }
    public int GroupID { get; set; }       
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
    public string YearOfBirth { get; set; }
    public DateTime CreationDate { get; set; }
    public CashUnited.Data.Repositories.BeneficiariesGroup.BeneficiariesGroup bgroup { get; set; }

}

 public class BeneficiariesGroup
{
    public int ID { get; set; }      
    public string Name { get; set; }
    public ICollection<CashUnited.Data.Repositories.Beneficiaries.Beneficiaries> beneficiary { get; set; }
}

我尝试了上述操作,但没有成功:无效的列名'bgroupID'

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您应该添加一个属性来跟踪您的FK。

public class Beneficiaries
{
    public int ID { get; set; }
    public string CUID { get; set; }
    public int GroupID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
    public string YearOfBirth { get; set; }
    public DateTime CreationDate { get; set; }
    public BeneficiariesGroup bgroup { get; set; }
    public int bgroupId { get; set; } // you need a porperty to keep your fk
}

...

builder.Entity<Beneficiaries>().HasOne(a => a.bgroup)
.WithMany(q => q.beneficiary)
.HasForeignKey(f => f.bgroupId);   

相关问题