MVC 5 select from 2 model linq expression - c#

For example i have 2 model.
ASpnetUserRoles and ASPnetRoles
i want to select ASPnetRoles.Name,ASPnetROles.ID where ASPnetRoles.ID in ASPnetUserRoles.
i only know how to write in SQL
select * from modalA where modelA.id in(select modelB.id from modelB)

if you enable "Lazy Loading" , you can use this linq query :
using(var db = ..."context"..)
{
var q = db.AspNetUserRoles.where(c=>c.UserID = userIdVal)
.select(z=> new { RoleId = z.RoleId
,userId = z.UserId
,RoleName = z.AspNetRole.RoleName
})
.toList();
}

This is what i did eventually.
IEnumerable<IdentityRole> ro;
ro = (from p in haha join ur in aspNetUser.AspNetRoles on p.Id equals ur.Id select p);

Here a generic sample you must create a class (no EF), and store the result to it.
IQueryable<ResultClass> result=from t1 in db.Table1
join t2 in db.Table2
//Here the relation fields
on t1.IdTable1 equals t2.IdTable2
//Here where conditios and/or orderby
select new ResultClass()
{
Field1=t1.SomeField,
Field2=t2.SomeField,
//all need fields
}
Use the result
result.ToList()

Related

How to join 3 tables with linq

I am trying to join 3 tables in a query with Linq to get data from all 3 tables. Below is an image of the table schemes:
The query should select: SewagePlantName, CompanyName and Duty
In addition I need to restricts the SewagePlantId to a list of Ids that are given as:
var sewagePlantIds = UnitOfWork.GetAll<UserGroup>()
.Where(group => group.Id == webAppPrincipal.GroupId)
.SelectMany(group => group.SewagePlantId).Select(sewageplant => sewageplant.Id).ToList();
I have difficulties with the order of joining the 3 tables and where/how to restrict the SewagePlantId to the given list.
Can you try something similar to it please for joining part
from d in Duty
join c in Company on d.CompanyId equals c.id
join s in SewagePlant on c.SewagePlantId equals s.id
select new
{
duty = s.Duty.Duty,
CatId = s.Company.CompanyName,
SewagePlantName=s.SewagePlant.SewagePlantName
// other assignments
};
var obj = from trns in context.tblPartyRegistrations
join st in context.tblSellingTrans
on trns.PartyRegId equals st.Fk_PartyRegId
join pt in context.tblPartyRemainings
on trns.PartyRegId equals pt.fk_PartyId
select new
{
trns.Name,
trns.PhoneNo,
trns.Address,
st.RecivedAmount,
st.Date,
st.CustomerType,
st.MilkRate,
st.Mltr,
st.Mkg,
st.NtAmnt,
st.RemaningAmount,
pt.Remainingammount
};

Including objects from join in query result

Imagine a simple Entity Framework query with a context generated from the database such as:
var q = from a in context.Accounts
join c in context.Contracts
on a.Id equals c.AccountId
select new CustomAccount {
Id = a.Id,
Name = a.Name,
...
Contracts = //How do I easily populate the related contracts?
};
The query looks for accounts and joins to contracts. The relationship is not enforced in the database (I can't change the schema) so I can't use navigational properties. Is there an easy way that I can populate the related objects?
Just use a group by clause. Something like this (untested):
var q = from a in context.Accounts
join c in context.Contracts on a.Id equals c.AccountId
group a by new { a.Id, a.Name, a.Etc } into g
select new CustomAccount
{
Id = g.Key.Id,
Name = g.Key.Name,
Etc = g.Key.Etc,
Contracts = g.SelectMany(x => x.Contracts)
};
I'm not sure if I understand correctly but you can execute a query that return anonymous type objects
EDIT : you can create a custom class to hold the data member of your result and return in linq result.
EDIT : using group by on account name (e.g)
var q = from a in context.Accounts
join c in context.Contracts
on a.Id equals c.AccountId
group a by new { a.Name } into g
select new AccountContracts
{
AccountName = g.Key.Id, // Account name
Contracts = g.SelectMany(x => x.Contracts)
};

Linq updating different table after join process

I have combined 3 of my tables by using linq join. After that i want to update this table by using data that i get from webform. How can i do this ? My implementation is below
public void updateShoes(Shoe shoe)
{
var query = from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
where shoe.ShoeID == s.ShoeID
orderby m.ModelName
select new
{
s.ShoeID,
s.Size,
s.PrimaryColor,
s.SecondaryColor,
s.Quantity,
m.ModelName,
m.Price,
b.BrandName
};
}
Though your approach is a little bit unclear right now (for e.g. we don't know which entities you are trying to update), however you can modify your code like this,
public void updateShoes(Shoe shoe)
{
var query = from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
where shoe.ShoeID == s.ShoeID
orderby m.ModelName
select new
{
Shoe = shoe, Brand = b, Model = m
};
foreach(var o in query)
{
o.Shoe.ColorName = "Black";
o.Brand.BrandName = "New Branding";
o.Model.ModelName = "Something else";
}
db.SaveChanges();
}
Rather picking selected properties from each Entity, you can pick whole entity. Then you can update each entity in a loop as I have doing above.
I like the all-in-one linq update. Especially if I need to join on an existing object list.
var UpdQuery = (from b in db.BrandTbls
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
where shoe.ShoeID == s.ShoeID
orderby m.ModelName
select new { b, m, s }
// now for the update portion of the query
).Select(result =>
{
result.s.ShoeID = shoe.ID;
result.s.Size = shoe.Size;
result.s.PrimaryColor = shoe.PrimaryColor;
result.s.SecondaryColor = shoe.SecondaryColor;
result.s.Quantity = shoe.Quantity;
result.m.ModelName = shoe.ModelName;
result.m.Price = shoe.Price;
result.b.BrandName = shoe.BrandName;
return result; // this is important
}).ToList(); // tolist actually runs the query to update the objects
db.SaveChanges(); // write changes back to DB
To update an entity you will need to retrieve the entity from the context, modify the values, then call SaveChanges() to do the update.
foreach( var n in query)
{
var shoe = db.Shoes.Find(n.ShoeID);
shoe.Size = webFormData.Size;
}
db.SaveChanges();

Linq with Lambda equivalent of SQL

I am relatively new to entity framework and I've been trying to write a Linq statement with Lambda that includes a simple join. I have three tables: Staff - StaffRole - Role.
I want a staff member in a certain role that satisfies a certain condition. Its very simple to write this in regular SQL:
SELECT *
FROM Staff s
INNER JOIN StaffRole sr ON s.StaffId = sr.StaffId
INNER JOIN Role r ON sr.RoleId = r.RoleId
WHERE r.Description = 'SpecialisedHealthManager'
AND s.PrimaryShm = 0
Now, writing it in a Linq statement has not given me much luck. I'm thinking it would be something like this:
var actingShm = db.Staff.Join(db.StaffRole,
inner => inner.StaffId,
outer => outer.Role,
(outer, inner) => new
{
StaffId = inner.StaffId,
FirstName = inner.Staff.FirstName,
Surname = inner.Staff.Surname,
SamAccountName = inner.Staff.SamAccountName,
RoleId = outer.Description
});
Needless to say, this is not working..
Try using it this way:
var list = from s in Staff
join sr in StaffRole on s.StaffId equals sr.StaffId
join r in Role on sr.RoleId equals r.RoleId
where r.Description == 'SpecialisedHealthManager' && s.PrimaryShm == 0
select new
{
StaffId = s.StaffId,
FirstName = s.Staff.FirstName,
Surname = s.Staff.Surname,
SamAccountName = s.Staff.SamAccountName,
RoleId = r.Description
});
Look here if you realy want to do this with method syntax LINQ:
SO Multiple tables join with lambdas
Also look here:
http://msdn.microsoft.com/pl-pl/library/bb534675(v=vs.110).aspx
for Join extension method syntax. Usage presented in your code is wrong.
You should have your associations setup so you can do this...
var actingShm = from s in db.Staff
from r in s.Roles
where r.Description == "SpecialisedHealthManager"
select new
{
StaffId = s.StaffId,
FirstName = s.FirstName,
Surname = s.Surname,
SamAccountName = s.SamAccountName,
RoleId = r.Description
});
Are you using Entity Framework or Linq2SQL?

What is the syntax for an inner join in LINQ to SQL?

I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.
How do you represent the following in LINQ to SQL:
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
It goes something like:
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
It would be nice to have sensible names and fields for your tables for a better example. :)
Update
I think for your query this might be more appropriate:
var dealercontacts = from contact in DealerContact
join dealer in Dealer on contact.DealerId equals dealer.ID
select contact;
Since you are looking for the contacts, not the dealers.
And because I prefer the expression chain syntax, here is how you do it with that:
var dealerContracts = DealerContact.Join(Dealer,
contact => contact.DealerId,
dealer => dealer.DealerId,
(contact, dealer) => contact);
To extend the expression chain syntax answer by Clever Human:
If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:
var dealerInfo = DealerContact.Join(Dealer,
dc => dc.DealerId,
d => d.DealerId,
(dc, d) => new { DealerContact = dc, Dealer = d })
.Where(dc_d => dc_d.Dealer.FirstName == "Glenn"
&& dc_d.DealerContact.City == "Chicago")
.Select(dc_d => new {
dc_d.Dealer.DealerID,
dc_d.Dealer.FirstName,
dc_d.Dealer.LastName,
dc_d.DealerContact.City,
dc_d.DealerContact.State });
The interesting part is the lambda expression in line 4 of that example:
(dc, d) => new { DealerContact = dc, Dealer = d }
...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields.
We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses dc_d as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.
var results = from c in db.Companies
join cn in db.Countries on c.CountryID equals cn.ID
join ct in db.Cities on c.CityID equals ct.ID
join sect in db.Sectors on c.SectorID equals sect.ID
where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)
select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };
return results.ToList();
You create a foreign key, and LINQ-to-SQL creates navigation properties for you. Each Dealer will then have a collection of DealerContacts which you can select, filter, and manipulate.
from contact in dealer.DealerContacts select contact
or
context.Dealers.Select(d => d.DealerContacts)
If you're not using navigation properties, you're missing out one of the main benefits on LINQ-to-SQL - the part that maps the object graph.
Use Linq Join operator:
var q = from d in Dealer
join dc in DealerConact on d.DealerID equals dc.DealerID
select dc;
basically LINQ join operator provides no benefit for SQL. I.e. the following query
var r = from dealer in db.Dealers
from contact in db.DealerContact
where dealer.DealerID == contact.DealerID
select dealerContact;
will result in INNER JOIN in SQL
join is useful for IEnumerable<> because it is more efficient:
from contact in db.DealerContact
clause would be re-executed for every dealer
But for IQueryable<> it is not the case. Also join is less flexible.
Actually, often it is better not to join, in linq that is. When there are navigation properties a very succinct way to write your linq statement is:
from dealer in db.Dealers
from contact in dealer.DealerContacts
select new { whatever you need from dealer or contact }
It translates to a where clause:
SELECT <columns>
FROM Dealer, DealerContact
WHERE Dealer.DealerID = DealerContact.DealerID
Inner join two tables in linq C#
var result = from q1 in table1
join q2 in table2
on q1.Customer_Id equals q2.Customer_Id
select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
Use LINQ joins to perform Inner Join.
var employeeInfo = from emp in db.Employees
join dept in db.Departments
on emp.Eid equals dept.Eid
select new
{
emp.Ename,
dept.Dname,
emp.Elocation
};
Try this :
var data =(from t1 in dataContext.Table1 join
t2 in dataContext.Table2 on
t1.field equals t2.field
orderby t1.Id select t1).ToList();
OperationDataContext odDataContext = new OperationDataContext();
var studentInfo = from student in odDataContext.STUDENTs
join course in odDataContext.COURSEs
on student.course_id equals course.course_id
select new { student.student_name, student.student_city, course.course_name, course.course_desc };
Where student and course tables have primary key and foreign key relationship
try instead this,
var dealer = from d in Dealer
join dc in DealerContact on d.DealerID equals dc.DealerID
select d;
var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName
}).ToList();
var data=(from t in db.your tableName(t1)
join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname
(where condtion)).tolist();
var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();
Write table names you want, and initialize the select to get the result of fields.
from d1 in DealerContrac join d2 in DealerContrac on d1.dealearid equals d2.dealerid select new {dealercontract.*}
One Best example
Table Names : TBL_Emp and TBL_Dep
var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id
select new
{
emp.Name;
emp.Address
dep.Department_Name
}
foreach(char item in result)
{ // to do}

Categories

Resources