I have 3 tables
table 1 = user table
table 2 = staff table
table 3 = userStaff table
userStaff table is the join table that connects the user and staff table.
user Table
id | firstName | password
---------------------------
2 | UserOne | hashed
staff Table
id | firstName | lastName
---------------------------
3 | sally | jones
userStaff Table
userID | staffID
---------------------------
2 | 3
I have created a method that inputs the user id and it should return back the staff table corresponding to the staffId linked to the userID. In this case, I want to insert the user id of 2 and get back the information of staff id 3, therefore receiving back " id = 3, firstName = Sally, lastName = jones".
This is the code I tried to use
public async Task<UserStaff> GetUserLinkStaff(int id)
{
var staff = await _context.UserStaffs
.FirstOrDefaultAsync(u => u.UserId == id)
.Include(s => s.staffs);
return staff;
}
However, I get an error message which says "Task' does not contain a definition for 'Include' and no accessible extension method 'Include' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly reference?) [Schedular.API]csharp(CS1061)"
What is the correct LINQ query I should use?
What is the correct LINQ query I should use?
To solve it, just change your code as follow:
var staff = await _context.UserStuffs.Include(o => o.Stuff)
.FirstOrDefaultAsync(u => u.UserId == id);
When using Include to get the associated data, you should first perform the Include operation after the DbSet, then return the associated data collection and get the specific data by FirstOrDefaultAsync method after Include.
I suggest you read this article to understand the usage of Include in ef core.
Here is the test result:
Related
I'd like to populate a dropdown list based on the selection chosen in the previous field.
Currently I have 2 Lists from my ViewModel like so:
Manufacturers = context.ManufacturersTable.OrderBy(x => x.ManufacturerName).ToList(),
Models = context.ModelsTable.OrderBy(x => x.ModelName).ToList(),
Both lists are populated using a SQL Table with their own data model.
In the Models table, I have a column for ManufacturerID which matches that of the ManufacturerID in the Manufacturers table.
I'd like to populate the Models list based on the selection of the Manufacturers list so that only models associated with the selected manufacturer are displayed.
How would I do this using Lambda?
I've been playing with Where and Select but haven't quite been able to get there.
EDIT:
Here's the tables
MANUFACTURER | MANUFACTURER_ID
Manufacturer 1 GUID1
Manufacturer 2 GUID2
MODEL | MODEL_ID | MANUFACTURER_ID
Model 1 | GUID1 | GUID1
Model 2 | GUID2 | GUID2
Model 3 | GUID3 | GUID1
Model 4 | GUID4 | GUID1
When you change the selection of the manufacturer field, call a controller method with manufacturer id as a parameter that returns:
context.ModelsTable
.Where(x => x.ManufacturerId == manufacturerId)
.OrderBy(x => x.ModelName)
.ToList();
...then update the select list with the result.
context.ModelsTable.Where(x => x.ManufacturerId == value).OrderBy(x => x.ModelName).ToList()
This doesn't work? Pass ManufactureId as value.
Where keyword filter data but returns all columns from the table. With Select you can select which columns you want to return. You can use these keywords together.
Say we have a table called as
Employee
___________________________________
ID | Name | Surname | DomainID
And another table
Domain
______________________
ID | Name | Type
where employee table has foreigh key to domain table
Now i want to write Entity Framwwork Migration such that whose domainID matched with filtering criteria and i want to change Domain.Type and say Employee.Surname.
Some thing like
1. var emp = Select all Employee where DomainID = 1;
Store the result in some varibale
2. loop through emp and do changes.
NOTE: I am using EntityFramework, and i dont want to create temporary tables to store data as it might be one time job.
I assume the below will do the trick
private void YourMethod(int domainId)
{
var filteredEmployees = Emoployees.Where(e=>e.DomainID == domainId).ToList();
foreach(Employee emp in filteredEmployees)
{
//do your logic
}
YourDBContext.SaveChanges();
}
I've a LTSQL query which returns all users and userroles from SQL Server DB.
For example one user can have many user roles. So in the returned query if you look at a single user row it will have EntitySet(UserRole) for each userRole
The C# LTSQL query which returns all the the relational data is simply
var results = from u in db.Users
Select u;
Gridview.DataSource = results;
Gridview.Databind;
This displays all the data from the user table but not the userroles which is an entity in the results from the query.
If I want to display the user info from users table and all the userroles on a single gridView row, what is the most efficient approach?
The gridView should look something like this:
UserId | UserName | UserRoles |
1 | John Smith | Admin, Accountant | Edit
2 | Dave Jones | Sales, Admin | Edit
Something like this:
var results = from u in db.Users
Select new {
UserID = u.UsrID,
UserName = u.UserName,
UserRoles = string.Join(", ", u.UserRoles.Select(r => r.Name))
};
Suppose I have a simple database schema with a customers and orders table with a foreign key from orders to customers, and a unique key on customer name.
Customers
-----------
[CustomerID] INT NOT NULL
[Name] VARCHAR(50) NOT NULL
Orders
-----------
[OrderID] INT NOT NULL
[CustomerID] INT NOT NULL
+------------+------+ +---------+------------+
| CustomerID | Name | | OrderID | CustomerID |
|------------+------+ +---------+------------+
| 1 | John | | 1 | 1 |
+------------+------+ +---------+------------+
I've set up LINQ to SQL entities in the obvious way, with a Customer entity and an Order entity with a one-to-many association from Customer to Order.
The issue I'm having comes when I want to enter a new order for John using my LINQ entities. I thought the way to do this would be to get the Customer entity for John and assign it to my Order entity, then submit that, but it's not working. Here's my C# code to do this.
using (var db = new DataClassesDataContext())
{
Order order = new Order();
Customer existingCustomer = db.Customers.FirstOrDefault(c => c.Name == "John");
if (existingCustomer == default(Customer))
{
Customer customer = new Customer();
customer.Name = "John";
order.Customer = customer;
}
else
{
order.Customer = existingCustomer;
}
db.Orders.InsertOnSubmit(order);
db.SubmitChanges();
}
I have verified that I am indeed assigning existingCustomer to my Order before submitting it, but despite this I still get a unique key constraint error when I attempt to submit.
I'm very new to LINQ to SQL, so I think I'm just going about this incorrectly. How should I implement my code to account for a unique constraint?
The line
db.Orders.InsertOnSubmit(order);
marks the whole object graph for insert. So if you move the line to just below Order order = new Order(); only the order is marked for insert. That means that for a new customer you must call InsertOnSubmit too.
I think your code should be fine. Somehow it tries to insert a new customer but that should not happen.
Can you try it with
Customer existingCustomer = db.Customers.Single(c => c.Name == "John");
and see if you get an exception? In that case there might be something wrong with the DBML for the customer table.
Not helping you with the question but vsince you have a unique constraint on the name Single / SingleOrDefault is better than First/FirstOrDefault.
I have two tables, in a many-to-many relationship, with a junction table, as follows:
Member MemberGroup Group
========= ============ =======
PK | ID PK | ID PK | ID
| Name | Member | Name
| Group
| MemberSince
I need to add all the members of a specific group to a list box. The group is selected from a data bound combo box. I was looking to do something like this:
listbox1.ItemsSource = DataModel.Members.Where(u=>u.Group == mygroup);
However, the Member entity only contains the MemberGroup entries.... not the actual groups.
What is the best way to do this?
By the way, .NET Framework 3.5, WPF, Entity Framework, C#, SQL Server Compact Edition (2008)
Found the solution.
public partial class Group
{
public ObjectQuery<Member> Members
{
get
{
return (from j in DataModel.MemberGroup
where j.Group.ID == this.ID
select j.Member) as ObjectQuery<Member>;
}
}
}