Как получить конкретное значение столбца, используя первичный ключ - сущность фреймворка? - PullRequest
0 голосов
/ 01 октября 2019

У меня есть разные таблицы. Например, таблица 1 содержит имя человека Таблица 2 содержит имя страны и идентификатор человека

Table 1:
PersonId     PersonName
1            John
2            Smith
3            Kelly


Table 2:
LocationId   Continent      Country     PersonId
1            Asia           Japan       1
2            Asia           China       2

// There is C# method where PersonId should be passed.. suppose id=2 is passed

var person = await _repository.Person.FirstOrDefaultAsync(x => x.PersonId == id); //This find Smith from DB
var location = await _repository.Location.FirstOrDefaultAsync(x => x.LocationId == person.PersonId);   
// location variable will get all values of second row from Table 2 i.e LocationID=2, Continent=Asia, Country=China, PersonId=2
// but i just need value of Country column i.e China of PersonId=2

// Though I can get CountryName from this -- have to write below extra code for that
var country = location.Country;   // this will get Country = China

How can I achieve this in a single line?

// something like
var location = await _repository.Location.FirstOrDefaultAsync(x => x.LocationId == person.PersonId).Country();

Ответы [ 3 ]

0 голосов
/ 01 октября 2019

Вам следует взглянуть на создание Навигационного свойства на объекте персонажа, чтобы EF мог автоматически сопоставить отношения для вас. Затем вы можете выбрать «Ленивая загрузка» или «загрузить страну» одним запросом с помощью include.

0 голосов
/ 01 октября 2019
//First Method :

Entity await _repository = new Entity() // object of your entity.
var Result = (from a in await _repository.Person.Where(a=>a.PersonId == id)
              from b in await _repository.Location.Where(b=>b.PersonId=a.PersonId)
              select new 
              {
                 a.PersonId,a.PersonName,b.Country
              }).SingleOrDefault();
Result.Country; // Here you can get country,also get other values PersonName,PersonId

//Second Method :

Entity await _repository = new Entity() // object of your entity.
var Result = (from a in await _repository.Location.Where(a=>a.PersonId == id)select 
              a.Country).SingleOrDefault(); //other wise you can select 'a'.  
Result.Country; // Here you can get country
0 голосов
/ 01 октября 2019

Использовать Выбрать

var country = await _repository.Location.Where(x => x.LocationId == person.PersonId).Select(l => l.Country).FirstOrDefault();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...