[英]How to make foreign key inside models for particular column of composite primary key in Entity Framework
[英]How to get the particular value of column using the primary key - entity framework?
我有不同的桌子。 例如,表 1 包含 Persons 的名稱 表 2 包含 Country name 和 Person Id
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();
使用Select
var country = await _repository.Location.Where(x => x.LocationId == person.PersonId).Select(l => l.Country).FirstOrDefault();
您應該查看在人 object 上創建導航屬性,以便 EF 可以自動為您 map 關系。 然后,您可以選擇延遲加載或在一個包含包含的查詢中急切加載國家/地區。
//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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.