Including a second query in Entity Framework LINQ Query - c#

I've got a table "Houses" and "Cats", which contains the columns "Id" and "HouseName" and "Id" and "CatName".
Now I got a table "HouseCatAssignments", where I store the relations between the Cats and the Houses (the Cat can live in more than one house and one house can store more than one cat).
This table looks like:
Id, CatId, HouseId
"CatId" is bound to Cats.Id and HouseId is bound to Houses.Id.
Now I want to display the Table "House" in a datagrid that also contains a field for "CatCount" - a counter for the value of how many cats are living in this house.
How should I now query my tables so I have all the values of "Houses" and an additional Column that contains the Cat-Count for the specific house?

For Entity Framework it should have automatically added navigation properties that allow you to do the following query:
var housesWithCount = context.Houses
.Select( h=> new
{
Id = h.Id,
HouseName = h.HouseName,
CatCount = h.Cats.Count()
});

Related

Entity Framework-Saving models with related tables

So my question basically has to do with nested models or associated tables (not sure the correct term).
Specifically when TableA has an ICollection of TableB objects and TableB has an ICollection of TableA, how do I then save off my entire TableA model along with it's assocaited Table2 items.
For example:
User table with: string name, string address, ICollection < Orders >
Orders table with: OrderID, Total, ShipDate, ICollection < User >
So I have a User instance (UserA) which has the name and address set along with a collection of orders (Let's say Bob Dole, 1234 Main st, [567, $12.34, Oct 1; 999, $27.89, Nov 5;]).
How do I trigger the save method to save both Orders & the User?
My expectation would be "db.User.add(UserA); + db.SaveChanges();". I would expect this to save the User and upon seeing the Orders collection, save those as well.
However, previous developers did this:
User userB = db.User.Add(new User(userA.Name, userB.address)); //Why do we have to create a 2nd instance of a User object, that will hold the same information as userA?
foreach(Order order in userA.orders)
{
Order NewOrder = db.Orders.Add(order); //This now updates the Orders table with new info, which will be saved by 'db.SaveChanges()'
NewOrder.User.Add(userB); //How does this update the value in the Orders table with the userID? Isn't this updating the object about to go out of scope?
}
db.SaveChanges()
The only thing we can think, is the way they did it userB get's 'ID' assigned from the .Add command. But couldn't you simply say "userA = db.Users.Add(userA)" in order to update the instance with the ID provided upon database insert?
First of all, I think, you've got to change your schema.
There will be one-to-many relationship between User and Orders. One user can have multiple orders but one order can not belong to multiple users. i.e. Only Order table would have UserId.
Update
Further, No need to add Orders data separately. As there would available collection type in the User table's entity.
You need to just assign values to the User table's entity along with Orders field and do insert it only once.
The code would be somehow as below:
var userData = user;
var orderData = orderCollection;
userData will be single record and orderData could be multiple.
Now assign that data to User data model:
var userAndOrder = new User
{
Name = user.Name,
Address = user.Address,
Orders = orderCollection.Select(o => new Order
{
//assign order fields here
}).ToList();
};
Then save this data. It will save Orders data itself in the Order table against the UserId.
db.Add(userAndOrder);
db.SaveChanges();

Create a table in SQL Server where the name is a variable in C#?

Using Visual Studio and SSMS.
I have a form where a user registers a username and it's stored like this:
List<SqlParameter> sqlNewTable = new List<SqlParameter>();
sqlNewTable.Add(new SqlParameter("Username", txtUser.Text));
DAL.ExecSP("CreateUserCourses", sqlNewTable);
From there, can I create a stored procedure called CreateUserCourses in which it creates a new table where the users input (their username) is the name of a new table?
Sure you can, but why?
Supposing you have a User table and a Course table. Then just make a 3rd table which maps those tables together Called UserCourses. This is called a Many-to-Many (mapping table) and it will containing an ID of both the User, and Course and any other relevant information .
This will make your life a lot easier going forward
Many-to-many (data model)
A many-to-many relationship is a type of cardinality that refers to
the relationship between two entities1 A and B in which A may
contain a parent instance for which there are many children in B and
vice versa.
For example, think of A as Authors, and B as Books. An Author can
write several Books, and a Book can be written by several Authors
Example
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id // mapping table
SQL queries could look like this
Getting all students for a class
SELECT s.student_id, last_name
FROM student_classes sc
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X
Getting all classes for a student
SELECT c.class_id, name
FROM student_classes sc
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y
Entity framework queries could look like this
Getting all students for a class
var students = db.Students.Where(x => x.StudentClasses
.Any(y => y.ClassId == 1);
Getting all classes for a student
var classes = db.classes.Where(x => x.StudentClasses
.Any(y => y.StudentId == 1);

Linq to Entity use relation of tables fill gridview

I have 3 Tables Customer,CustomerTicket,Ticket
Customer-->ID primary key
CustomerTicket-->ID,TicketNo where ID,TicketNo are foreign-key
Ticket-->TicketNo,Subject where TicketNo primary key
I am using linq to entity and want to show columns like this,
ID TicketNo Subject
1 12 Car
1 18 Home
2 23 Plane
Every unique ID can have Many TicketNo and every TicketNo has one unique Subject
Gridview.DataSource=from customer in entity.Customer
join custicket in entity.CustomerTicket on customer.ID equals custicket.ID .....
I tried code like the above but in the end couldn't understand how to make the table as I want.How will code continue or is there any better way? Also note that entity framework took my CustomerTicket table and add it as navigation property ...
Do the joins, create an anonymous collection with select, create a binding datasource with the collection and set the datasource
var cusList=from customer in entity.Customer
join custicket in entity.CustomerTicket on customer.ID equals custicket.ID
select new
{
custicket.ID,
custicket.ticketno,
ticket.subject
};
var bs = new BindingSource();
bs.DataSource=cusList;
Gridview.DataSource=bs;

Add a many-to-one predicate to a LINQ-to-SQL query

How do I filter an IQueryable<T> LINQ-to-SQL query on a related many-to-many table? For example, given an IQueryable<Product> where each Product has many Tags that are stored in a related ProductTags table, I want to filter on the association of one or more tags.
A document store or comma-separated value on Product would make this simpler, but the data are stored in denormalised SQL tables.
For bonus points, what if the ProductTags table is just a mapping-table and I also need to retrieve data from the Tags table?
This is what the schema looks like:
Products <-> ProductTags <-> Tags
Update: Looks like I want to filter against an EntitySet<T>.
If you've got a list of tag names, say tagNames, you can do something like:
var query = from p in Products
from t in p.ProductTags.Select(pc => pc.Tag)
where tagNames.Contains(t.TagName)
select new { p.ProductName, t.TagName };
This will get you all Product that have at least one of the tags in tagNames and you can select data from Product or Tag.
Note that this is not necessarily a distinct list of products.
If the tags are stored in ProductTags directly, the query changes into
var query = from p in Products
from t in p.ProductTags
where tagNames.Contains(t.TagName)
select new { p.ProductName, t.TagName };

How do I insert a record with the key of the previous record in one call?

In my database, I have a table called Department that columns named DepartmentID (PK) and SubdepartmentOfID (FK). SubdepartmentOfID is constrained as a FK to DepartmentID in order to basically create a hierarchical type relationship.
What I'm trying to do in Entity Framework 6 is to create a default subdepartment that has the same name as the department, but in order to do so, I need to be able to set the SubdepartmentOfID before inserting it though my context, right? Currently, I'm using this logic:
Create the entity, insert it, save it (this ends up populating the DepartmentID key in the entity).
Create another entity for the subdepartment and set its SubdepartmentOfID property equal to that of the previously saved entity, save it
I feel like this could be done in one call. Can it?
This answer assumes the following:
You're using database first (using the designer) as opposed to code first
You have a table named Department with the following columns
DepartmentID
SubDepartmentID
DepartmentName
I think you can do this.
var department = new Department
{
DepartmentName = "D1"
};
var subDepartment = new Department
{
DepartmentName = "D1"
};
department.Department = subDepartment;
context.Departments.Add(department);
context.SaveChanges();
Entity framework will now take care of the autogenerated IDs and associate the sub department to the department.

Categories