Asp.net/SQL - Retrieving data from multiple tables using foreign keys - c#

I'm new to ASP.NET and SQL, and I'm trying to build a Web Forms project that will basically display data using grids.
I'm using Entity Framework along with a Data Transfer Object and a Data Access Layer for displaying/editing data.
My issue is that I'm not sure what is the best way of retrieving data using foreign keys.
Example:
Table 1 - Products
|(PK) Product ID | Product Name | Country ID(FK)
Table 2 - Countries
|(PK) Country ID | Country Name|
Final Result Should be:
Product ID | Product Name | Country Name|
What's the best way to accomplish that?
Thanks in advance

The best approach is use a projection to do that.
Your code will be similar to the code below:
context.Products.Select(x=>new ProductDto
{
ProductId=x.ProductId,
ProductName=x.Name,
CountryName=x.Country.Name
});
Using projections you will ensure that is retrieving only the necessary data from DB.
Hope this helps!

You can make LINQ query from this one. Better, you create one separate class and retrieve only data which you want.
SQL Query :
SELECT P.ProductID, P.ProductName, C.COuntryName FROM Products P
INNER JOIN ON Countries C ON C.CountryID = P.CountryID
Execute Query using EF :
context.Database.SqlQuery<ProductDTO>(query).ToList();

Related

How to update multiple tables using one query in Entity Framework?

I want to update three table with one Query in Entity Framework:
Customer_Identification Region Customer Account
| Id |Region_Id |Customer Id
| Name |Region_Name |Bank_Name
| Address |Bank Account
| Region_Id
I created a class Customer with all fields required and I used a join query to select what information I want to update in database.
I try to update changes in this way :
dataContext.Entry( Customer).State = System.Data.Entity.EntityState.Modified;
dataContext.SaveChanges();
I get this error:
The entity type DbQuery`1 is not part of the model for the current context.
How is possible to update database without using multiple queries?
Best regards,

Entity Framework 6 mapping a custom SQL query to an Entity

I am very new to ASP.NET MVC and Entity Framework at the moment. I've been working with it for about 3 months at the current moment in time.
I have an ASP.NET MVC 5 application that's running Entity Framework 6. This is a code first approach from an existing database with auto migrations enabled so all of my Entity classes are auto generated. I am trying to add a view to my MVC application that returns a specific result set. Currently the previous developer has the application set up to only accept an Entity class to display data to a DataTable DataTables.net. To clarify further:
I have two Entity tables in my model that are tables in MySQL.
| Samples | SampleLocation |
|:------------------|---------------:|
| Id | LocationId |
| DateAssigned | Name |
| CheckedInDate | Size |
| SampleLocationId | |
| ...etc | ...etc |
What I'm trying to accomplish is querying both tables and returning the results to my MVC application in a view. From there run an Update and update a couple of columns in the Samples table. Below is the roughly the query that returns the results I need.
SELECT Samples.Id, samples.CheckedInDate, SampleLocation.Name, SampleLocation.Size,
SampleLocation.LocationId
FROM (Samples join SampleLocation
ON ((Samples.SampleLocationId = SampleLocation.LocationId)))
WHERE isnull(samples.CheckedInDate) ORDER BY samples.Id
From the research that I have done there are a few ways to accomplish this. The ways that I've tried that would give me a class I could use are creating a stored procedure and then updating the model - this breaks the model and unmaps every single entity in the model. I have tried creating a view with the query to add to the model - but this breaks it as well and unmaps everything. I later found out that this is a bug.
So my question is, how can I map a query to an Entity that return results to a view? Is there a better way to go about this?
There are several ways to accomplish what you want to do, using either Entity Framework only or extra tools like Dapper
Entity Framework Only:
First you can use Linq to extract the data, I'll look something like this:
var list = from s in Samples
join l in SampleLocations
on s.Id equals l.LocationId
where s.CheckedInDate == null
select new
{
s.Id,
s.CheckedInDate,
l.Name,
l.Size,
l.LocationId
};
Dapper:
The second method is using dapper, the only real difference here is that you would be working with your queries directly, so instead of linq you had something like this:
Connection.Query(#"SELECT Samples.Id, samples.CheckedInDate,
SampleLocation.Name, SampleLocation.Size,
SampleLocation.LocationId
FROM Samples
join SampleLocation
ON Samples.SampleLocationId = SampleLocation.LocationId
WHERE isnull(samples.CheckedInDate) ORDER BY samples.Id");
For both:
In your update method, you first have to retrieve the entities, for that you can use the DbSet.Find method or another query, after that you call DbConext.SaveChanges.
This is the solution to my problem. Basically manually creating an Entity within the XML and mapping it to a virtual table.Entity Framework DefiningQuery

Connect to multiple tables or join two tables in ASP.NET MVC C#

Sorry if the title was confusing.
Lets say I have a model called Employee. Employee has a column called Departments. This allows them to view the calendar for that department. But some Employees should be able to view the calendar for multiple departments, and it is different for every employee.
Because there are many different departments, I do not want to have the Employee table filled with a ton of new columns for each department.
I saw something about linking (not sure if that is the right word) two tables. So I made a second model/table called AdditionalDepartments that has the AdditionalDepartmentsId, EmployeeId, and Department.
Say Joe was part of department A but can also view B and C. This is what employee looks like.
EmployeeId | name | Department
-------------------------------
1 | Joe | IT
and the AdditionalDepartments would look like...
AdditionalDepartmentsId | EmployeeId | Department
--------------------------------------------------
1 | 1 | HR
2 | 1 | Sales
How would I go about combining these? Or is there a better way to store additional department information rather than two tables?
I ask because in my view, when they create or edit an employee, they use the employee database, but I want to be able to set additional departments on these views. The problem with that is you can only use one model per view so I am having difficulties.
Note: I cannot drop the Department from Employee because it is used for a lot more than what the AdditionalDepartments would be used for.
Change your first table column to something like OfficialDepartment. In your second table, drop the 'Additional' and just leave it as Departments. Add 'IT' to this table for 'Joe' as well. Then output the SQL using the statement below into a List<Departments> into your model and use as needed.
select A.Departments as [Departments]
from Employees E
join Departments D on E.EmployeeId = D.EmployeeId
where E.EmployeeId = <empId>
You would want the Employee model to have an IEnumerable<Department> that contains all the Departments that employee is a part of.
On a somewhat unrelated note, if you have the ability to change the table schema at all, you could just drop the Department column in the first table, and make the second table just be a list of departments associated with employees based on the employeeID columns (they would have a foreign key relationship).
Sorry if I misunderstood your question, but unless you are taking one database to be a single model, this should do the trick for you.

Entity Framework select single value from row

I am using Entity Framework from .NET 3.5
I have two tables with 0-1 to many relation. Let's say Citizen and City. Each citizen has foreign key column (ID) that connects him to City.
When i select single citizen, i also need to select the name of the city where he lives.
Because city table contains tons of data that is not really related to citizen, so i don't want to retrieve it from database to save some bandwidth.
Currently i am using Include() function, but it grabs all the data from the City related to citizen, while i need only name.
Is there a way to write a query to select single cell from the whole row in EF and without creating new classes or interfaces or repositories?
Here is my Include:
Citizen citizen = db.Citizens.Include("Cities").First(p => p.citizen_id == id);
You do this by projecting, e.g.
var c = from c in db.Citizens
where c.citizen_id == id
select new
{
Name = c.Name,
CityName = c.City.Name
};
You can also project onto POCOs.
You cannot tell the EF to retrieve an object of type Citizen with a related City but with only City.Name filled in. The EF will not partially materialize an entity. Use view / presentation models or DTOs instead of entities when you need only a few fields.

How do IN () statements work in NHibernate? (Using Criteria)

I'm trying to create the equivalent of the below using NHibernate. I've done all the mappings using fluent and I can do the basic queries just fine but I have no idea how to do this.
-**Product Table**
Reference
Title
Subjects (Many to Many relationship)
Price
-**Subject table**
SubjectID
Name
-**SubjectToProductMapping Table**
Reference
SubjectID
Now I need to do this:
SELECT *
FROM Product
WHERE Reference IN
(Select Reference FROM SubjectToProductMapping WHERE SubjectID = #SubjectID)
Baring in mind the Product table has been simplified a great deal for the post and that I would prefer to use an IN statement to keep the rest of the query simpler. I would ideally like to create the query using Criteria becuase I will be using Criteria to page the results.
Thanks in advance
Why would you use an in when a join would suffice? provided your Products class has a mapped collection of subjects then you could just use this Criteria
IList<Product> results = session.CreateCriteria(typeof(Product))
.CreateCriteria("Subjects", JoinType.Join)
.Add(Resitctions.Eq(Projections.ID, subjectID))
.List<Product>();

Categories