Joining tables in Entity Framework - c#

I have a table called Students and a table called Majors, Students and Majors are joined by MajorId I have set this relationship already and have set the foreign key in the schema. When I access my Student object how can I return the MajorName column (this comes from the Majors table)? The only options I have in intellisense is Major_1, Major_1Reference, MajorId .

Major_1 should be a navigation property leading to the appropriate Major entry, so you should be able to access the Major's properties like this:
from s in ctx.Students
select s.Major_1.MajorName

You can use linq join statement like this to make query on the two tables...
var q = from s in Students
join m in Majors on s.MajorId equals m.MajorId
select new { m.MajorName };

Related

Linq Multiple Joins

I have some sql tables that I need to query information from my current query that returns a single column list is:
from f in FactSales
where f.DateKey == 20130921
where f.CompanyID <= 1
join item in DimMenuItems
on f.MenuItemKey equals item.MenuItemKey
join dmi in DimMenuItemDepts
on item.MenuItemDeptKey equals dmi.MenuItemDeptKey
group f by dmi.MenuItemDeptKey into c
select new {
Amount = c.Sum(l=>l.Amount)
}
This returns the data I want and it groups correctly by the third table I join but I cannot get the Description column from the dmi table. I have tried to add the field
Description = dmi.Description
but it doesnt work. How can I get data from the third table into the new select that I am creating with this statement? Many thanks for any help.
Firstly you are using Entity Framework COMPLETELY WRONG. Linq is NOT SQL.
You shouldn't be using join. Instead you should be using Associations.
So instead, your query should look like...
from sale in FactSales
where sale.DateKey == 20130921
where sale.CompanyID <= 1
group sale by sale.Item.Department into c
select new
{
Amount = c.Sum(l => l.Amount)
Department = c.Key
}
By following Associations, you will automatically be implicitly joining.
You should not be grouping by the id of the "table" but by the actual "row", or in Object parlance (which is what you should be using in EF, since the raison d'etre of an ORM is to convert DB to Object), is that you should be grouping by the "entity" rather than they the "entity's key".
EF already knows that the key is unique to the entity.
The grouping key word only allows you to access sale and sale.Item.Department after it. It is a transform, rather than an operator like in SQL.

LINQ: get city name from foreign table address

I have two Restaurant and Location tables. Location table has foreign key LocationId stored in Restaurant table. I want to select city name from location table, while getting some information from Restaurant table too. How can I retrieve it using C#.
Thanks in advance.
var cityNameAndSomeRestaurantStuff = from r in Db.Restaurants
join l in Db.Locations
on r.LocationId equals l.LocationId
select new { l.CityName, r.SomeProperty };
Note that the result will be an IQueryable, so if you want it materialised, call .ToList() or some similar extension

Linq Query to Get Distinct Records from Two Tables

I have two Tables - tblExpenses and tblCategories as follows
tblExpenses
ID (PK),
Place,
DateSpent,
CategoryID (FK)
tblCategory
ID (PK),
Name
I tried various LINQ approaches to get all distinct records from the above two tables but not with much success. I tried using UNION and DISTINCT but it didnt work.
The above two tables are defined in my Model section of my project which in turn will create tables in SQLite. I need to retrieve all the distinct records from both the tables to display values in gridview.
Kindly provide me some inputs to accomplish this task. I did some research to find answer to this question but nothing seemed close to what I wanted. Excuse me if I duplicated this question.
Here is the UNION, DISTINCT approaches I tried:
DISTINCT # ==> Gives me Repetitive values
(from exp in db.Table<tblExpenses >()
from cat in db.Table<tblCategory>()
select new { exp.Id, exp.CategoryId, exp.DateSpent, exp.Expense, exp.Place, cat.Name }).Distinct();
UNION # ==> Got an error while using UNION
I think union already does the distict when you join the two tables you can try somethin like
var query=(from c in db.tblExpenses select c).Concat(from c in
db.tblCategory select c).Distinct().ToList();
You will always get DISTINCT records, since you are selecting the tblExpenses.ID too. (Unless there are multiple categories with the same ID. But that of course would be really, really bad design.)
Remember, when making a JOIN in LINQ, both field names and data types should be the same. Is the field tblExpenses.CategoryID a nullable field?
If so, try this JOIN:
db.Table<tblExpenses>()
.Join(db.Table<tblCategory>(),
exp => new { exp.CategoryId },
cat => new { CategoryId = (int?)cat.ID },
(exp, cat) => new {
exp.Id,
exp.CategoryId,
exp.DateSpent,
exp.Expense,
exp.Place,
cat.Name
})
.Select(j => new {
j.Id,
j.CategoryId,
j.DateSpent,
j.Expense,
j.Place,
j.Name
});
You can try this queries:
A SELECT DISTINCT query like this:
SELECT DISTINCT Name FROM tblCategory INNER JOIN tblExpenses ON tblCategory.categoryID = tblExpenses.categoryID;
limits the results to unique values in the output field. The query results are not updateable.
or
A SELECT DISTINCTROW query like this:
SELECT DISTINCTROW Name FROM tblCategory INNER JOIN tblExpenses ON tblCategory.categoryID = tblExpenses.categoryID;<br/><br/>
looks at the entire underlying tables, not just the output fields, to find unique rows.
reference:http://www.fmsinc.com/microsoftaccess/query/distinct_vs_distinctrow/unique_values_records.asp

Getting collection from foreign key

In such a two tables
table Person
{
int Id -> primary key
varchar name
varchar nick
int GroupId -> foreign key
}
table Group
{
int Id -> primary key
varchar name
}
If I use
var result = (from c in myDataBase.Group
select c).ToList<Group>();
I get only list of Group, but field System.Data.Objects.DataClasses.EntityCollection<Person> is empty. How should I change query to get also list of Persons?
It's not clear where System.Data.Objects.DataClasses.EntityCollection<Person> has to be, but I presume you are searching for Inner join
var query = from person in people
join group in groups on person.GroupId equals group .Id
select new {.. something... };
Here I presumed you have somewhere people (collection of Person types) and want to find all persons from that collection and their matching information from related Group.
If this is not what you're asking for, please clarify.
I solved problem with:
myDataBase.Group.Include("Person").Select(a => a).ToList();
Btw: what is equivalent of Include() in linq query from...where...select ?

Fluent NHibernate join not using primary key

I am trying to get a single property from a joined table where a non-PK in my main table is joined to the PK of the foreign table. Below is an oversimplified example of what I am trying to accomplish (I do not want to reference the foreign entity):
Tables:
CREATE TABLE Status
(
Id int,
Body text,
CategoryId int
)
CREATE TABLE Category
(
Id int,
Name text
)
SQL to generate:
SELECT Id, Body, CategoryId, Category.Name AS CategoryName
FROM Status
LEFT JOIN Category ON Category.Id = Status.CategoryId
I am trying to map the join like this in the StatusMap but it seems to be joining on the two primary keys (where Status.Id = Category.Id):
Join("Category" m =>
{
m.Optional();
m.KeyColumn("CategoryId");
m.Map(x => x.CategoryName, "Name");
});
As far as I know the only way around this using Fluent is to map to a view as you currently are doing. Join() will always map to the primary key of the parent table. The KeyColumn method specifies the key column for the child table only, which in your case is the Category table.
To achieve the desired SQL using your simplified version above you'd probably want to use References to define a many-to-one relationship between status and category.

Categories

Resources