Entity Framework select single value from row - c#

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.

Related

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

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();

Entity Framework with table join to another database with Code First

I have an EF code first application. I have a column PersonId that I need to join with another database (warehouse) table Persons which contains all the people in our organization.
I have read that one solution is to use a view then make my entity model from the view but this seems quite painful if we have a PersonId column in many tables.
How best to return back all rows from table A joined with a table B from another database on key column PersonId, really to return PersonDisplayName from table B?
There has got to be a best practice for this situation?

How does the EF store relationship inside SQL Server Express? (very confused)

I have a question regarding the way the Entity Framework stores relationships between objects inside SQL Server Express 2008 as I'm pretty confused right now.
I'm working on an WPF/MVVM application using EF. For the sake of simplicity, I'm gonna use an example.
Lets say I have two tables in SQL Server, Customer and Orders. Customer has a primary key ID (uniqueidentifier) and Orders does have one too. Now Orders does also have a column called CustomerId (uniqueidentifier) on which I define a relationship to the Customer.ID column.
These tables map to Entity Framework objects Customer and Order.
What I usually do when creating a new Order would be this:
Order newOrder = Context.CreateObject<Order>();
newOrder.Id = Guid.NewGuid();
newOrder.CustomerId = customer.Id;
In this case, in the database (after saving the context) all the columns in Orders are filled with data.
Now this time I did this:
Order newOrder = Context.CreateObject<Order>();
newOrder.Id = Guid.NewGuid();
newOrder.Customer = customer; //so I'm assigning the Customer object to the relationship, not the ID
When doing it this way, I would also expect that in the database, after saving the context, the column Orders.CustomerId would have a value (the Customer's GUID). However, in my case, it does NOT. However, when I navigate the Customers collection in my WPF application, all the Orders appear under the right Customer. (I did restart the application multiple times, so the context is newly created). Also tested on another machine. So there is no cache thingie.
So I was wondering, how can EF know which Order belongs to which Customer even though the database does not hold the necessary information inside its table's columns? Or is there some place else where this info is stored automagically?
I am very very confused as of right now.

Comparing SQL tables and getting Values using Entity Framework

I have three tables viz: Person(PersonID(INT), Personname(varchar)) , Items(ItemID(INT), Itemname(varchar)) and PersonItemAssoc(PersonItemAssoc(Int), PersonID(INT), ItemID(INT)).
PersonItemAssoc is having many to many association for personid and Itemid.
I want to get way in which if I pass the itemId, I should get all the PersonIds which dont have an association witn this ItemId in the PersonItemAssoc table.
I am using Entity Framework 4.0.
Please suggest a way for implementing this.
var peopleWithoutItem = from p in Context.Person
where !p.PersonItems.Any(pi => pi.Item.ItemId == someItemId);
select p;
Note that if you get rid of PersonItemAssoc(int) and make the PersonItemAssoc PK the compound of PersonID and ItemID then the EF can do People to Items as a many to many, instead of two 1 to many relationships.

Entity Framework Many-To-Many with additional field on Joining Table

I have an entity context that includes three tables. The first is a table that contain products, the second contains recipes. The joining table has fields for IDs in both the products and recipes table as well as a 'bit' field called 'featured'.
I've searched and found no example on how to insert only how to select against this type of scenario.Does anyone have any suggestions on how this can be done? Thanks in advance for any help.
I didn't do C# for a while, so I am not sure my syntax is valid, anyway this should be the idea:
Products product = new Products { Blah, Blah, Blah };
bool flag = false;
for (int i = 0; i < 5; i++)
{
Products_Receipes pr = new Products_Receipes
{ Products = product, IsFeatued = flag };
pr.Receipes.Add(new Receipes());
pr.Receipes.Add(new Receipes());
flag = !flag;
}
Context.SaveChanges();
And if the above doesn't work, then let me just tell you that you have to create the main item (either Products or Receipes), then when you create the Products_Receipes set it's Products/Receipes property to the above (or by Products.Pruducts_Receipes.Add(pr)), then add the other side of the relation the same way.
An observation is that your diagram is structured more like a DB schema than an entity diagram. Entities should be designed to meet the business needs independent of the data storage structure so you can use any DB to store the data.
I believe you can remove the "Link" entity and set up a one-to-many or many-to-many associations between Products and Recipes. Then setup your DB schema w/ the link table and do the Table Mapping accordingly.

Categories