How can I do this query? - c#

can You help me in this situation
I have three tables
first stored usersgroup
ugroup - primary key
groupname - group name
second stored users
uid - primary key
ugroup - int
username
and so on
.....
third table has list of teachers for each user
teachId - primary key
uid - int
..........
so this query work fine in controller
var viewUsers= db.UsersGroup.Include("Users").ToList();
and in view
I can outp all my groups and users which are in them
#foreach(var ug in #Model.viewUsers)
{
ug.groupName
foreach(var u in ug.Users)
{
u.UserName;
}
}
so but I want to build table in view to show this info:
<caption>GroupName</caption>
<th>UserName</th><th>Count of teachers</th>
<td> John Smith</td><td>3</td>
So how should i build a query to build table in my View like above?
And I if you can give some link where can i read about how can i use EF to make varios queries to my database (like joins uinions and otheres) and I don't understand how work Include() method
i try to chnge my prev string like : db.UserGroups.Include(ug => ug.Users) but it does not work :(
Thank You.

var viewUsers= db.UsersGroup.Include("Users.Teachers").ToList();
and then in the view you can get the Teacher list for each user
#foreach(var ug in #Model.viewUsers)
{
ug.groupName
foreach(var u in ug.Users)
{
u.UserName;
<th>u.Teachers.Count</th>
foreach(var teacher in u.Teachers)
{
<td>teacher.Name</td>
}
}
}

Related

Retrieve foreign key values in Linq

I have 2 tables
User
Access
In the user table I have 4 columns in total but 1 in foreign key of another table (Access).
UserId
UserName
UserEmail
AccessId(FK)
And in the Access table I have 2 columns
AccessId
Yes/NO
I'm able to retrieve the UserId but not AccessId because it is a foreign key in User table.
Here is the code I have written
var test = (from userName in User
select userName.AccessId).ToList();
This is the result I get
System.Collections.Generic.List`1
I want to get the AccessId as well, can you help me please?
Well
var test = (from userName in User
select userName.AccessId).ToList();
Returns a list, so that is what you get. A list of AccessID's.
If you need the ID;s
foreach (var aSingleAccessID in test)
{
// do something with each accessID
}

Include unrelated table in Linq to entity query

I have the following simplified setup:
Public User
{
//Primary key
public int Id {get;set;}
public string Name {get; set;}
}
Public UserInfo
{
//Primary key
public int Id {get;set;}
//Foreign key to user table
public int userKey {get; set;}
}
The relationship between the tables is one user to Many userInfo
I am trying to select from the user table and include the userInfo table.
I cannot do this:
var users = Context.user.Include(u => u.userInfos);
as there is no reference to the UserInfo table from the user table.
I can do this:
context.userInfo.include(x => x.user)
but if there are no corresponding entries in the userInfo table, this will not return any results, which is not what I want. Also, this will return one row for each userInfo, whereas I want one row for user, with a list of userInfo as a parameter.
Similarly I could join the tables like this:
var users = from us in Context.user
join inf in Context.userInfo
on us.Id equals inf.userKey
select new //etc
But this will also return one row per userInfo entry, the same problem as above.
To summarise, is there a way of including this table to produce a result in the same way as the include function does.
I know I could adjust my setup to all me to include this, but that is not what I am asking here.
I suspect this cannot be done, but from all my googling so far I have not been able to find a definitive answer....
I want one row for user, with a list of userInfo as a parameter
I assume you mean a list of userInfo as a property. My understanding of what you ask it that you're just looking for:
var users = from us in Context.user
join inf in Context.userInfo
on us.Id equals inf.userKey into infg
select new
{
User = us,
UserInfos = infg
};
join ... into amounts to a GroupJoin, i.e. a user entity joined with a group of userinfos.
Better still is to use a navigation property user.userInfos (reluctantly following your naming convention):
var users = Context.user.Include(u => u.userInfos);

DeleteObject from multiple tables

I am trying to delete the movie from rentals table if it is selected from the listbox and it is working but i also need to remove datas connected to the movie from rentingpeople table
Rentals table contains the movieid which is in the listobox and personid which can be also found in rentingpeople and should get deleted the full row if they matches.
var search = (from g in db.Rentals where g.Movietitle == (string)lBfilmlista.SelectedValue select g).First();
foreach (var c in db.Rentingpeople where c.personid==search.personid).First();
{
db.Rentingpeople.DeleteObject(c);
}
db.Rentals.DeleteObject(search);
db.SaveChanges();
there is code error at where c.personid==search.personid ) ; expected
Problem is with First at the end of foreach loop, and also mixing query syntax with method syntax.
So your code should be:
var search = (from g in db.Rentals where g.Movietitle == (string)lBfilmlista.SelectedValue select g).First();
var rowsToBeDeleted = db.Rentingpeople.Where(c=> c.personid==search.personid).ToList();
foreach (var item in rowsToBeDeleted)
{
db.Rentingpeople.DeleteObject(item);
}
db.Rentals.DeleteObject(search);
db.SaveChanges();
You can also setup Cascade on Delete rules for your tables.

Inputting Customer.customerID into Advert.cutomerID using LinQ to Sql in MVC3 Razor

Been at this far too long; trying to populate a field in a record with a foreign key, it is dependent on which user is logged on.
Shown below is a view bag which displayed the Firstname of the customer in a dropdown, which the user had to select. It would then put the CustomerID into the record when it was created. This method was impractical
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "FName");
Below is an attempt to input the foreign key automatically by finding the CustomerID and then inputting the custoemrID into a hidden field on a form.
public ActionResult Create()
{
var CusID = from c in db.Customers
where c.UserName == "User.Identity.Name"
select c.CustomerID;
return View(new CarAdvert { UserName = #User.Identity.Name, CustomerID = CusID });
}
The error: Cannot implicitly convert type system.linq.Iqueryable <-int-> to int
The approach taken (is this correct! - Any advice on the subject welcome)
any more info need please ask.
Regarding the error:
var CusID = (from c in db.Customers
where c.UserName == User.Identity.Name
select c.CustomerID).Single();
Instead of .Single you can/should use .First, .FirstOrDefault, ... depending on your requirements.

Problem in Inserting or Updating in many to many relationship EF4

Let's say have 3 tables:
Category
-------------
CategoryID int
Title text
Admin
------------
AdminID int
FullName text
Permission
------------
CategoryID int
AdminID int
AllowAccess bit
When i try to update changes to database i got following exception:
Unable to insert or update an entity because the principal end of the 'KiaNetModel.FK_Permissions_Admins' relationship is deleted.
WHY?
The function that update changes:
public static void SetPermissions(int[] cats, int userId, Entities context)
{
var premissions = from p in context.AdminPremissions where p.AdminID == userId select p;
// Clear all premissions...
foreach (var p in premissions)
{
p.AllowAccess = false;
}
foreach (var c in cats)
{
var es = from e in context.AdminPremissions where e.CategoryID == c && e.AdminID == userId select e;
// If any pre permission was found, set flag = true
if (es.Count() > 0)
es.First().AllowAccess = true;
// Otherwise add new one
else
context.AdminPremissions.AddObject(new AdminPremission() { AdminID = userId, CategoryID = c, AllowAccess = true });
}
}
It's an web application, and when user mark permissions, i could only determine which permissions are set, not all of them.
If you have any other idea, or better way please tell me.
I think relationship between tables Permission and Admin has been deleted from either Actual database or from Entity Model. It it is the case then u have to create that relationship again.
Generate "Admin" Table And "Permission" Drop And Create Script (With Data - If U Have Data On it).
Then Execute It, If U Have Relation Re Create It,
Ur Prb Must Be Solve.

Categories