I am trying to populate a object with additional data from another object with Entity Framework from our data tables.
public partial class Maintable
{
public int Id { get; set; }
public int ConnectionID { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
public partial class Jointable
{
public int Id { get; set; }
public int ConnectionID { get; set; }
public string Value { get; set; }
}
The goal is to fill the value from join table > Value (which can be null/empty) to the main table > Value column and select/return the main table object.
The tables are only connected with the ConnectionID column, not the actual IDs (can't change that sadly). Also these tables are not related to eachother, it comes from separate tools, which are only sharing the ConnectionID column, which is also not a key of any type in this tables.
I tried something like this:
var model = from mt in db.Maintable
join jt in db.Jointable on mt.ConnectionID equals jt.ConnectionID into gj
from x in gj.DefaultIfEmpty()
select new {
mt,
mt.Value = x != null ? x.Value : "" }
Model should only return main table object.
The SQL equivalent should be like this:
SELECT
mt.Id AS ID,
mt.ConnectionID AS ConnectionID,
mt.Name AS Name,
jt.Value AS Value
FROM
Maintable mt
LEFT JOIN
Jointable jt ON mt.ConnectionID = jt.ConnectionID
I hope this is understandable, I couldn't really find something because I'm not sure what exactly to search for... Sorry if this has already been answered.
{get:set}?? That's a typo, right?Blogentity/class has aPostscollection. Justcontext.Blogs.Include(b=>b.Posts).Where(b=>b.AuthorID=34)is enough. It's the ORM's job to generate joins based on the relations. EF will load an entire graph of related objects at a time, not table rowsFromSqlto execute that query and map the results to classes. Or you could define the relation onConnectionIdinstead of the actual primary keys. EF may be able to handle this precisely because it's not a database model