Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

fetching data from one to one table to parent tb

$
0
0

Hi,

I'm fairly new to linq. I am having trouble with a query that i suppose is very easy but i'm not sure how to do it.

i have a class that holds all the data(named PersonData). this data comes from two tables that have a one to one relationship.  a Person table with a Company table.

how would i write the correct/best query for this? how do i get the Company data into it? what if the Coompany table don't exist?

var person = from d in _context.Persons 
select new PersonData
{
  Name = d.Name,
  Age = d.Age,
  Company = d.Company.Name
};
var dto = person.FirstOrDefault(i => i.ID == id);

how about using AsNoTracking() and/or includes like this: this works, 

var person = from d in _context.Persons.Include(c => c.Company)
select new PersonData
{
  Name = d.Name,
  Age = d.Age,
  Company = d.Company.Name
};
var dto = person.AsNoTracking().FirstOrDefault(i => i.ID == id);


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>