Отношение один ко многим в фреймворке Entity dbcontext - PullRequest
0 голосов
/ 10 февраля 2020

У меня есть две таблицы в базе данных следующим образом

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 Ответ

1 голос
/ 10 февраля 2020

Вы должны добавить свойство, чтобы отслеживать ваши FKs.

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);   

...