Получить значение из другой таблицы по идентификатору с Entity Framework - PullRequest
0 голосов
/ 04 июля 2018

У меня есть две таблицы уже существующих (без использования ключа):

Клиент (Id, Name, .....) Проекты (Id, CustomerId, name)

И в моем основном приложении asp.net у меня есть две модели:

public class Customer {
   public int Id { get; set; };
   public String Name { get; set; };
}

public class Project {
   public int Id { get; set; };
   public Customer Customer{ get; set; };
   public String Name{ get; set; };
}

И классы datacontext для этого

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

    public DbSet<CustomerContext> Customer { get; set; }
}

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

    public DbSet<ProjectContext> Project{ get; set; }
}

Но я не могу узнать, как получить объект Customer в Projectclass по customerId

Может кто-нибудь помочь мне, пожалуйста? Спасибо

Редактировать: Теперь я изменяю свои классы моделей, как в ответе ниже

но со следующим я получаю исключение SQL при загрузке страницы SqlException: Неверное имя объекта «Клиент».

        projectList = await (from project in _context.Project
                                     join customer in _customerContext.Customer on project.CustomerId equals customer.Id into tmp
                                     from m in tmp.DefaultIfEmpty()

                                     select new Project
                                     {
                                         Id = sollIst.Id,
                                         CustomerId = sollIst.CustomerId,
                                         Customer = m,
                                         Name = sollIst.Name,
                                     }
                      ).ToListAsync();

Ответы [ 3 ]

0 голосов
/ 04 июля 2018

Вам нужно будет создать свойство в классе Project, которое будет представлять «внешний ключ».

Допустим, в таблице Project в базе данных "внешний ключ" - это CustomerID, добавьте его в класс Project:

public int CustomerID { get; set; }

Затем добавьте атрибут ForeignKey в свойство Customer:

[ForeignKey("CustomerID")]
public Customer Customer { get; set; }
0 голосов
/ 04 июля 2018

Обновите классы вашей модели, как показано ниже:

public class Customer {
   public int Id { get; set; };
   public String Name { get; set; };
}

public class Project {
   public int Id { get; set; };
   public String Name{ get; set; };
   public int CustomerID { get; set; }
   [ForeignKey("CustomerID")]
   public Customer Customer{ get; set; };
}

Слияние обоих DbContext в один.

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

    public DbSet<Project> Projects { get; set; }
    public DbSet<Customer> Customers { get; set; }
}

Затем выполните

projectList = await (from project in _context.Project
                 join customer in _context.Customer on project.CustomerId equals customer.Id into tmp
                 from m in tmp.DefaultIfEmpty()

                 select new Project
                 {
                     Id = sollIst.Id,
                     CustomerId = sollIst.CustomerId,
                     Customer = m,
                     Name = sollIst.Name,
                 }
  ).ToListAsync();

Я надеюсь, что следующие ссылки помогут вам узнать, как объединить две таблицы в разных базах данных.

  1. Объединение таблиц из двух баз данных с использованием структуры сущностей.
  2. Структура сущностей объединяет две базы данных
0 голосов
/ 04 июля 2018

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

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

   public string Name { get; set; };
}

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

   [ForeignKey("Customer")]
   public int CustomerId{ get; set; };

   public string Name{ get; set; };

   public Customer Customer { get; set; };
}

Тогда ваши классы DbContext должны быть следующими:

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

    public DbSet<Customer> Customers { get; set; }
}

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

    public DbSet<Project> Projects { get; set; }
}

Теперь вы можете использовать Entity Framework Core и запрос LINQ, чтобы получить нужные данные.

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