C# 如何使用主键-实体框架获取列的特定值?
我有不同的桌子。 例如,表1包含人员的姓名 表2包含国家名称和个人IdC# 如何使用主键-实体框架获取列的特定值?,c#,entity-framework-6,C#,Entity Framework 6,我有不同的桌子。 例如,表1包含人员的姓名 表2包含国家名称和个人Id Table 1: PersonId PersonName 1 John 2 Smith 3 Kelly Table 2: LocationId Continent Country PersonId 1 Asia Japan 1 2 Asia
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();
使用
您应该考虑在person对象上创建一个映射,以便EF可以自动为您映射关系。然后,您可以使用include在一个查询中选择延迟加载或快速加载国家/地区。方法是为Person类指定一个国家/地区属性并
include()
ing该导航属性。你试过什么?
//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
//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