Отношения между тремя таблицами с Entity Framework - PullRequest
0 голосов
/ 10 апреля 2020

Я хочу установить связь между тремя таблицами.

Моя база данных выглядит так: https://ibb.co/VggWGRb

А это мои классы:

public class Equipment     // model for Equipment table
{
    public int EquipmentID { get; set; }
    public IEnumerable<string> Item { get; set; }
}

public class Car     // model for car table
{
    public int CarID { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public int Price { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public int Production { get; set; }
    public int Mileage { get; set; }
    public byte[] ImageData { get; set; }
    public string ImageMimeType { get; set; }
}

public class CarEquipment        // model for carequipment table
{
    public int CarID { get; set; }
    public int EquipmentID { get; set; }

    public virtual Car Car { get; set; }
    public virtual ICollection<Equipment> Equipment { get; set; }
}

public class EfDbContext : DbContext
{
    public DbSet<Car> Cars { get; set; }
    public DbSet<Equipment> Equipments { get; set; }
    public DbSet<CarEquipment> CarEquipments { get; set; }
}

Я нашел какое-то решение, где кто-то использовал context.Guild.Include("Player").ToList();

Может быть, я должен сделать что-то подобное?

public class EFCarEquipmentRepository : ICarEquipmentRepository
{
    private EfDbContext context = new EfDbContext();

    public IEnumerable<CarEquipment> CarEquipment
    {
        get
        {
            return context.CarEquipments;
        }
    }
}

public interface ICarEquipmentRepository
{
    IEnumerable<CarEquipment> CarEquipment { get; set; }
}

Как правильно написать и как назвать модель автомобиля с его IEnumerable<string> equipment в контроллере?

1 Ответ

0 голосов
/ 10 апреля 2020

Согласно диаграмме ER, показанной на изображении в вашем вопросе, вы можете определить отношения в EF следующим образом:

 public class Equipment     // model for Equipment table
{
    public int EquipmentID { get; set; }
    public IEnumerable<string> Item { get; set; }
    public virtual ICollection<CarEquipment> CarEquipments { get; set; }
}

public class Car     // model for car table
{
    public int CarID { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public int Price { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public int Production { get; set; }
    public int Mileage { get; set; }
    public byte[] ImageData { get; set; }
    public string ImageMimeType { get; set; }
    public virtual ICollection<CarEquipment> CarEquipments { get; set; }
}

public class CarEquipment        // model for carequipmeHnt table
{
    public int CarID { get; set; }
    public int EquipmentID { get; set; }

    public virtual Car Car { get; set; }
    public virtual Equipment Equipment { get; set; }
}

public class EfDbContext : DbContext
{
    public DbSet<Car> Cars { get; set; }
    public DbSet<Equipment> Equipments { get; set; }
    public DbSet<CarEquipment> CarEquipments { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>().HasKey(x => x.CarID);
        modelBuilder.Entity<CarEquipment>().HasKey(x => new { x.CarID, x.EquipmentID });
        modelBuilder.Entity<Equipment>().HasKey(x => x.EquipmentID);
        modelBuilder.Entity<CarEquipment>().HasOne(x => x.Equipment).WithMany(x => x.CarEquipments);
        modelBuilder.Entity<CarEquipment>().HasOne(x => x.Car).WithMany(x => x.CarEquipments);
    }
}

И теперь вы можете получить доступ к CarEquipment вместе с Car следующим образом:

public class EFCarEquipmentRepository : ICarEquipmentRepository
{
    private EfDbContext context = new EfDbContext();

    public IEnumerable<CarEquipment> CarEquipment
    {
        get
        {
            return context.CarEquipments.Include(x => x.Car);
        }
    }
}

Если вы также хотите получить доступ к оборудованию, просто включите метод, подобный этому,

context.CarEquipments.Include(x => x.Car).Include(x => x.Equipment)

Примечание. Это один из лучших источников, где можно научиться определять отношения в EF Core: MS Do c

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...