Foreign key relationships in Entity Framework v.1 - linq

I need to be to create an entity data model in the EF version 1, because my web host doesn't have Framework 4.0 yet. Below is just a simple example to show the problem.
I have 3 tables, one Users table, another Webpages table, and one table with Visits. The former two tables each have a one-to-many relationship with the Visits table (which basically works as a many-to-many relationship, only the Visits table has its own primary key and extra fields)
With the 4.0 version this works, but it doesn't with v.1. "Visits" has a count of 0, so the test string returns ""... Why, and how would I be able to access the foreign key relation in v.1?
UsersEntities context = new UsersEntities();
var users = context.Users;
string result = "";
foreach (var user in users)
{
foreach (var visit in user.Visits)
{
result += visit.Webpage.Url + "\n";
}
}
So the foreach loop loops through the users, which it gets ok, but the inner loop is never entered because there are no Visits returned. Again, in Framework 4.0 it works fine, using the same database.
So what's wrong?

Simply change your code to this:
UsersEntities context = new UsersEntities();
var users = context.Users.Include("Visits");
string result = "";
foreach (var user in users)
{
foreach (var visit in user.Visits)
{
result += visit.Webpage.Url + "\n";
}
}
Notice the Include(...) that tells EF to eagerly load each User's visits.
With that in place it should work.
Actually if Webpage is a navigation too, you might need:
Include("Visits.Webpage");
Hope this works

Related

Laravel Eloquent model architecture and pivot table with composite keys

I have a Laravel specific problem, maybe caused by creating database model without previous Eloquent knowledge, and now I am really struggling with correctly retrieving required data.
Situation:
There are 4 entity models: Connection, Order, Seat, AdditionalItem.
Connection has X seats. You can create an Order, for Y connections, and for X seats for every connection, if available. And for every connection seat you can have N Additional items.
So for example, I can create and order for one connection with 2 seats, and another connection with 3 seats. And for some seats I can order additional items.
What I did is this:
I created a pivot table called "order_connection_seats", with composite keys "order_id", "connection_id", "seat_id" and some other attributes. It made total sense to me, because without need to create autoincrement primary keys I can easily store what i need. What looks to me little dirty is the solution for additional items. I have another pivot table "order_connection_seat_additional_items" with keys "order_id", "connection_id", "seat_id" and "additional_item_id".
The problem is, that when I try to correctly select data to be able to iterate over it, the query gets quite complicated and even doesn't work correctly.
What I need to do is something like (without lazy loading):
$orders = Order::query()->with(['connections' => ...])->get();
foreach ($orders as $order) {
foreach ($order->connections as $connection) {
foreach ($connection->seats as $seat) {
foreach ($seat->additionalItems as $additionalItem) {
}
}
}
}
OR
$connections = Connection::query()->with(['orders' => ...])->get();
foreach ($connections as $connection) {
foreach ($connection->orders as $order) {
foreach ($order->connection->seats as $seat) {
foreach ($seat->additionalItems as $additionalItem) {
}
}
}
}
Is this achievable with Eloquent, or is the data model incorrect and should be made differently to ge the desired result?
Thank you in advance.

How to save record in database using belongs to many relation in laravel

I have three tables: restaurant_location, cuisine_restaurant_location and cuisines.
There is a list of all cuisines in my cuisines table. I have all the details of the restaurant in my restaurant_location table. A restaurant can have many cuisines so I made a table cuisine_restaurant_location in which there are two columns cuisine_id and restaurant_id. I have created a belongs to many relation in my restaurant_location model.
restaurant_location model
public function cuisines()
{
return $this->belongsToMany(Cuisine::class, 'cuisine_restaurant_location', 'restaurant_id', 'cuisine_id');
}
I have a form in which all the details of the restaurant along with cuisines is supposed to be added. Right now I am adding all the details of the restaurant. Now the question is how can I insert the cuisines in "cuisine_restaurant_location".
Controller
$rest = new restaurant_location;
$rest->name = $request->input('name');
$rest->description = $request->input('desc');
$rest->save();
$cuisine = new cuisine_restaurant_location
$cuisine_lists = $request->input('cuisines');
foreach ($cuisine_lists as $cuisine_list) {
$cuisine->name = $cuisine_list;
}
You can use the sync and attach methods, described in the Many to many section of the eloquent documentation, for that:
$rest->cuisines()->attach([$cuisineIds])
Where cuisineIds is the list of ids of the cuisines you want to relate.
The difference between sync and attach is that sync will remove all id's not present on the array of ids you are passing.
Try sync() method:
$h = [];
if (isset($input["cuisine_id"])) {
$h = $input["cuisine_id"];
}
$restaurant_location->cuisines()->sync($h);

Should you join entities and merge them into a POCO?

There are times where I have to display the relationship between two entities. Question is, should you retrieve the data all in one query (with a join statement)?
For example, I have the entity User and Picture. A picture is created by one user. If I wanted to display list of picture names, and who uploaded the certain picture.
Two approaches:
1) Using Entity Framework relationship, where Pictures is an entity, and it has a User property (the user that created it). The User is an entity too.
foreach(var picture : context.Pictures.all){
picture.name
picture.user.name
}
2) Combining Picture & User into one POCO object and return that to the controller.
Controller:
foreach(var pictureUser : dal.GetPictureUsers){
pictureUser.PictureName
pictureUser.UserName
}
GetPictureUsers()
{
PictureUser pictureUserPoc = new PictureUsersql.Include("Picture").include("User").Select(sa=> new PictureUser {
PictureName = sa.PictureName,
UserName = sa.UserName});
}
The latter one was suggested in order to increase performance. Personally I would have written it in the former way since you do not couple what you want in the View logic (having Picture and User relationship printed) in the data access layer.
I hope I have stated the question clearly.
Thanks!
#foreach (var profile in Model)
{
#Html.DisplayFor(model=>profile.PictureName);
#Html.DisplayFor(model=>profile.User.Name);
}
The Model represents the Pictures; if you strongly type the view then you can use it.

How to update with Entity Framework in asp.net mvc3?

I Have a table in my databse that one of the columns named NumOfView shows the number of clicks on a link. That link shows some info from a row in this table. I used onclick event in anchor tag like this:
onclick=#Url.Action("NumOfClicks", "AdvertiseHelper",new { id = Model.id[i] })
In NumOfClicks function I used this code
public void NumOfClicks (int id)
{
Ad ad1 = new Ad();
var advert = (from ad in storedb.Ads where ad.AdId == id select ad.NumOfView).First();
advert += 1;
}
advert
is the amount of
NumOfView
in table that I want to increase it 1 unit. but I don't know how to continue coding for update this value in table. Can anybody help me please?
This is the basics of how it should be done. First you have to select the record itself from the database rather than the number of clicks. Increment the number of clicks on that record, then submit the changes to the DataContext.
public void IncrementClickCount(int id)
{
var advert =
(from ad in storedb.Ads
where ad.AdId == id
select ad).Single(); // Select the row in the database represented by "ad"
advert.NumOfView++; // Perform the increment on the column
// SubmitChanges is how an update is done in Linq2Sql
// This requires a .dbml file for the database object file
// storedb.SubmitChanges(); // Assumes storedb is a valid DataContext, updates
// SaveChanges is how an update is done in EntityFramework
// It is recognizable because it uses an .edmx file for its database object
storedb.SaveChanges();
}
This was similarly asked in SO question: Entity Framework - Update a row in a table

Displaying records from database which are equal to logged on user

I have created an MVC3 application which needs to show user specific data. The problem I am having is trying to display records which are equal to #user.Identity.Name.
The following Linq to SQL has been used to try to accomplish this:
public ActionResult Index()
{
using (var db = new mydatEntities())
{
var details = from t in db.testadtas
where t.UserID == Viewbag.UsersRecord
select t;
return View();
}
}
(Update)
New to c# and Linq and finding it hard to write a query which will only display the logged on users records.
I have used the code below
MembershipUser currentUser = Membership.GetUser (User.Identity.Name, true /* userIsOnline */);
Viewbag.UsersRecord = currentUser.ProviderUserKey;
I have then input the Viewbag.UserRecord into a textbox which updates a database field with the UserID in a table I have created.
I now want to write a linq query to say if UserID = Viewbag.UserRecord then show record with the UserID only
Is this a correct method to use for showing logged on user records?
or is there any other way which I can implement this in MVC3?
Just use HttpContext.User.Identity.Name

Resources