Entity Framework select Parent/Child Ordering by a .Include field - entity-framework-4

I have a simple Parent/Child table and I want to populate with one SQL statement using Entity Framework. Something like this:
public class Parent
{
public long ParentId { get; set; }
public virtual List<Child> Children { get; set; }
}
public class Child
{
public long ChildId { get; set; }
public long ParentId { get; set; }
public DateTime DateCreated { get; set; }
}
public Parent GetParent (long parentId)
{
IQueryable<Parent> query =
(from a in db.Parents.Include("Children")
where a.ParentId == parentId
select a);
return query.FirstOrDefault();
}
This seems to work in fetching the Parent and all Children in one SQL Statement. What I want to do now is order the children list by the DateCreated field, but I can't figure out how to do that. I've seen posts about using ThenBy() but don't see how to inject in the above Linq. Is there a better way I should be formulating the Linq?
-shnar

Unfortunately this is not supported. You cannot order included records by Linq-to-entities. Only parent records can be ordered. But you can still do something like:
var parent = GetParent(id);
var orderedChildren = parent.Children.OrderBy(c => c.DateCreated);

Related

Multiple tables update MVC .net

I am new to MVC and this is my function. There are three tables (Order, OrderNotes, Notes), ID is their primary key. One Order can have many Notes, the table OrderNotes has foreign key OrderID(from Booking table) and NotesID(from Notes table). I want to have a Order Edit page to display individual Order (FirstName, LastName), also display a list of its Notes. Here is my DB structure:
Booking table:
{ID,
FirstName,
LastName
}
BookingNotes table:
{ID,
BookingID,
NotesID
}
Notes table:
{ID,
NoteName,
StatusID
}
So how can I implement the list of Notes since it's from multiple tables? It will be able to Create New Note, Delete existing Note in the list row record, not Edit. Linq used in DB query. Thanks.
It would be a better idea to have only 2 tables:
public class Book
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// Navigational properties
public virtual List<Note> Notes { get; set; }
}
public class Note
{
public int ID { get; set; }
public int BookID { get; set; }
public string NoteName { get; set; }
public int StatusID { get; set; }
// Navigational properties
public virtual Book Book { get; set; }
public virtual Status Status { get; set; }
}
A third table is useful when you want to reuse the same Note for a different booking. However i think this is not the case.
So to retrieve data for your context make sure you have the DbSet<Book>
public class ApplicationDbContext : DbContext
{
public virtual DbSet<Book> Bookings { get; set; }
}
In your controller (or better in a repository class):
var BookingID = 10; // this is parameter passed to the function
var myBooking = this.dbContext.Bookings
.Include(p => p.Notes)
.ThenInclude(p => p.Status)
.FirstOrDefault(p => p.ID == BookingID);
Map the retrieved booking to a ViewModel, pass it to the View and you're good to go.

Use Entity framework I want to include only first children objects and not child of child(sub of sub)

Useing Entity framework I want to include an only the first level of children objects and not the children of child
I have these two classes:
public class BusinessesTBL
{
public string ID { get; set; }
public string FirstName { get; set; }
public string lastName { get; set; }
public ICollection<OffersTBL> OffersTBLs { get; set; }
}
public class OffersTBL
{
public int ID { get; set; }
public string Name { get; set; }
public int CatId { get; set; }
public string BusinessesTBLID { get; set; }
public virtual BusinessesTBL BusinessesTBLs { get; set; }
}
when I try to bring all offers according to CatId field, I need to return the BusinessesTBLs also, but the method also return offers again per each BusinessesTBL obj , My code is :
public IQueryable<OffersTBL> GetOffersTBLsCat(int id)
{
db.OffersTBLs.Include(s => s.BusinessesTBLs);
}
You can see the wrong result on :
http://mycustom.azurewebsites.net/api/OffersApi/GetOffersTBLsCat/4
As you can see it return all offers under each Business object while business object under each offer, And I want only to return offers with its Business object without offer under Business obj.
Could anyone help please?
I now see that a big part of the original answer is nonsense.
Sure enough, the reason for the endless loop is relationship fixup. But you can't stop EF from doing that. Even when using AsNoTracking, EF performs relationship fixup in the objects that are materialized in one query. Thus, your query with Include will result in fully populated navigation properties OffersTBLs and BusinessesTBLs.
The message is simple: if you don't want these reference loops in your results, you have to project to a view model or DTO class, as in one of the other answers. An alternative, less attractive in my opinion, when serialization is in play, is to configure the serializer to ignore reference loops. Yet another less attractive alternative is to get the objects separately with AsNoTracking and selectively populate navigation properties yourself.
Original answer:
This happens because Entity Framework performs relationship fixup, which is the process that auto-populates navigation properties when the objects that belong there are present in the context. So with a circular references you could drill down navigation properties endlessly even when lazy loading is disabled. The Json serializer does exactly that (but apparently it's instructed to deal with circular references, so it isn't trapped in an endless loop).
The trick is to prevent relationship fixup from ever happing. Relationship fixup relies on the context's ChangeTracker, which caches objects to track their changes and associations. But if there's nothing to be tracked, there's nothing to fixup. You can stop tracking by calling AsNoTracking():
db.OffersTBLs.Include(s => s.BusinessesTBLs)
.AsNoTracking()
If besides that you also disable lazy loading on the context (by setting contextConfiguration.LazyLoadingEnabled = false) you will see that only OffersTBL.BusinessesTBLs are populated in the Json string and that BusinessesTBL.OffersTBLs are empty arrays.
A bonus is that AsNoTracking() increases performance, because the change tracker isn't busy tracking all objects EF materializes. In fact, you should always use it in a disconnected setting.
You have deactivated lazy loading on OffersTBLs making it non-virtual. What if you activate lazy loading? like this:
public class BusinessesTBL
{
public string ID { get; set; }
public string FirstName { get; set; }
public string lastName { get; set; }
//put a virtual here
public virtual ICollection<OffersTBL> OffersTBLs { get; set; }
}
Then, be sure to not call/include OffersTBLs when serializing. If the OffersTBLs are still returning, it is because you are fetching them somewhere in your code. If this is happening, edit your question and paste all the code, including the serializing logic.
Since OffersTBL has an association to BusinessesTBL and BusinessesTBL to OffersTBL you can loop infinitly throw the Entities like OffersTBL.BusinessesTBL.OffersTBL.BusinessesTBL and so on.
To control the nested depth of the Entities i'm usually using helperclasses with the needed properties in them.
For BusinessesTBL
public class BusinessesTBLHelper
{
private BusinessesTBLHelper(BusinessesTBL o){
ID = o.ID;
FirstName = o.FirstName;
lastName = o.LastName;
OffersTBLids = new List<int>();
foreach(OffersTBL offersTbl in o.OffersTBLs){
OffersTBLids.Add(offersTbl.ID);
}
}
public string ID { get; set; }
public string FirstName { get; set; }
public string lastName { get; set; }
public IEnumerable<int> OffersTBLids { get; set; } //no references anymore
}
And same for your OffersTBL Entity.
public class OffersTBLHelper
{
private OffersTBLHelper(OffersTBL o){
ID = o.ID;
Name = o.Name;
CatId = o.CatId;
BusinessesTBLID = o.BusinessesTBLID;
BusinessesTBLs = new BusinessesTBLHelper(o.BusinessesTBLs);
}
public string ID { get; set; }
public string Name{ get; set; }
public intCatId{ get; set; }
public string BusinessesTBLID { get; set; }
public BusinessesTBLHelper BusinessesTBLs { get; set; }
}
On quering database you can directly create the new helperobjects from queryresult:
public IEnumerable<OffersTBLHelper> GetOffersTBLsCat(int id)
{
return db.OffersTBLs.where(s => s.CatId == id).Select(x=> new OffersTBLHelper(x)).ToList();
}
Now you have all the OffersTBL with BusinessesTBLs under. The loop stops here because the BusinessesTBLs have no OffersTBL under it. However, it only has them Ids in a List for further referencing and identifying.
Assuming that the object isnt null and just empty:
public IQueryable<OffersTBL> GetOffersTBLsCat(int id)
{
db.OffersTBLs.Include(s => s.BusinessesTBLs).Where(x => !x.BusinessesTBLs.OffersTBLs.Any());
}
Edit: Filter before the include:
public IQueryable<OffersTBL> GetOffersTBLsCat(int id)
{
db.OffersTBLs.Where(x => !x.BusinessesTBLs.OffersTBLs.Any())
.Include(s => s.BusinessesTBLs);
}

Bind comments to my entites in EF

I´am just in the beginning of creating a comment system for my website. I´am using EF and I want to bind a few of my tables to the Comments table. We can say that I have a Car entity and a Bike entity in two separate tables, and I would like to bind a collection of comments of these two tables.
In my mind I have a picture that the comments table would contain:
CommentID | EntityID | CommentText
1 Bike_2 Hello world..
2 Car_2 --
3 Bike_3 --
Am I thinking right? How do a setup this with entity framework?
Best regards.
(The following is for Entity Framework 4.1 to 4.3.1 and Code-First/DbContext.)
The type of mapping which comes closest to your idea is Table-per-Type (TPT) inheritance mapping. It would look like this:
public abstract class EntityWithComments
{
public int Id { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int Id { get; set; }
public string CommentText { get; set; }
public int EntityId { get; set; }
public EntityWithComments Entity { get; set; }
}
public class Car : EntityWithComments
{
public string Manufacturer { get; set; }
public string Color { get; set; }
}
public class Bicycle : EntityWithComments
{
public int Weight { get; set; }
public bool HasThreeWheels { get; set; }
}
EntityWithComments is a base class for Car and Bicycle and perhaps other entities. Then you have a derived DbContext class:
public class MyContext : DbContext
{
public DbSet<EntityWithComments> EntitiesWithComments { get; set; }
public DbSet<Comment> Comments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.ToTable("Cars");
modelBuilder.Entity<Bicycle>()
.ToTable("Bicycles");
}
}
As a result you have four tables in the database:
A Comments table which looks like your proposal but EntityId won't refer directly to the Cars and Bicycles tables. Instead it refers to the base type table EntitiesWithComments.
A table EntitiesWithComments representing the abstract base class and which only has a single column, namely the Id column.
A table Cars with a one-to-one shared primary key constraint between the Id and the Id in table EntitiesWithComments
A table Bicycles with a one-to-one shared primary key constraint between the Id and the Id in table EntitiesWithComments
You can then - for example - load all blue cars:
using (var ctx = new MyContext())
{
var blueCars = ctx.EntitiesWithComments.OfType<Car>()
.Where(c => c.Color == "Blue")
.ToList();
}
Because the EntitiesWithComments base table does not contain any column except the Id there is no join between the tables necessary. The generated SQL looks like this and only touches the table for the derived type:
SELECT
'0X0X' AS [C1],
[Extent1].[Id] AS [Id],
[Extent1].[Manufacturer] AS [Manufacturer],
[Extent1].[Color] AS [Color]
FROM [dbo].[Cars] AS [Extent1]
WHERE N'Blue' = [Extent1].[Color]
(I guess, the strange 0X0X value in this query is kind of a type descriptor EF uses to check if the returned rows are really cars, but I am not sure.)
If you want to load all bicycles with three wheels including their comments the following query works:
using (var ctx = new MyContext())
{
var bicyclesWithThreeWheelsWithComments = ctx.EntitiesWithComments
.Include(e => e.Comments)
.OfType<Bicycle>()
.Where(b => b.HasThreeWheels)
.ToList();
}

How to update complex model in ASP.NET MVC 3

I am trying to update a complex model in a single view.
I am using ASP.NET MVC3, Entity Framework with Code first, unit of work, generic repository pattern..
but when I try to update the model, i come up with this error:
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
Here is my simplified view model:
public class TransactionViewModel
{
public Transaction Transaction { get; set; }
public bool IsUserSubmitting { get; set; }
public IEnumerable<SelectListItem> ContractTypes { get; set; }
}
Here is my simplified complex model, and as an example one of its navigation property.
Transaction has one to one relationship with all of its navigation properties:
public class Transaction
{
[Key]
public int Id { get; set; }
public int CurrentStageId { get; set; }
public int? BidId { get; set; }
public int? EvaluationId { get; set; }
public virtual Stage CurrentStage { get; set; }
public virtual Bid Bid { get; set; }
public virtual Evaluation Evaluation { get; set; }
}
public class Bid
{
[Key]
public int Id { get; set; }
public string Type { get; set; }
public DateTime? PublicationDate { get; set; }
public DateTime? BidOpeningDate { get; set; }
public DateTime? ServiceDate { get; set; }
public string ContractBuyerComments { get; set; }
public string BidNumber { get; set; }
public DateTime? ReminderDate { get; set; }
public DateTime? SubmitDate { get; set; }
}
Using the same view model, I am able to create a transaction object, which would populate the database like this.
Id: 1, CurrentStageId: 1, BidId: 1, EvaluationId: 1
but, when I try to update properties within these navigation properties, this line causes the error, in controller:
[HttpPost]
public ActionResult Edit(TransactionViewModel model)
{
if (ModelState.IsValid)
{
-> unitOfWork.TransactionRepository.Update(model.Transaction);
unitOfWork.Save();
return RedirectToAction("List");
}
}
In generic repository:
public virtual void Update(TEntity entityToUpdate)
{
-> dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
The problem is further complicated because I should be able to edit any of the fields(properties) within any of the navigation property within Transaction object within a single view.
I believe that the exception means the following:
The property values that define the referential constraints ... (these are the primary key property (= Id) value of Bid and the foreign key property (= BidId) value of Transaction)
... are not consistent ... (= have different values)
... between principal ... (= Bid)
... and dependent ... (= Transaction)
... objects in the relationship.
So, it looks like the following: When the MVC model binder creates the TransactionViewModel as parameter for the Edit action, model.Transaction.BidId and model.Transaction.Bid.Id are different, for example:
model.Transaction.BidId.HasValue is true but model.Transaction.Bid is null
model.Transaction.BidId.HasValue is false but model.Transaction.Bid is not null
model.Transaction.BidId.Value != model.Transaction.Bid.Id
(The first point is probably not a problem. My guess is that you have situation 2.)
The same applies to CurrentStage and Evaluation.
Possible solutions:
Set those properties to the same values before you call the Update method of your repository (=hack)
Bind TransactionViewModel.Transaction.BidId and TransactionViewModel.Transaction.Bid.Id to two hidden form fields with the same value so that the model binder fills both properties.
Use also a ViewModel for your inner Transaction property (and for the navigation properties inside of Transaction as well) which is tailored to your view and which you can map appropriately to the entities in your controller action.
One last point to mention is that this line ...
context.Entry(entityToUpdate).State = EntityState.Modified;
... does not flag the related objects (Transaction.Bid) as modified, so it would not save any changes of Transaction.Bid. You must set the state for the related objects to Modified as well.
Side note: If you don't have any additional mapping with Fluent API for EF all your relationships are not one-to-one but one-to-many because you have separate FK properties. One-to-One relationships with EF require shared primary keys.

How do I display data from multiple tables in a single MVC view

I am having a hard time solving the following with an MVC view.
My goal is to display data from multiple tables in a single MVC view. The bulk of the data comes from a table called Retailers. I also have another table called RetailerCategories which stores the retailerid from the Retailers table and also a categoryid linking to a Category table.
Note that there are multiple records for each retailerid in the RetailerCategories table.
In the view I want to show a list of retailers and with each retailer I want to show the list of categories applicable to them.
What would be the best way to accomplish this? Some of the things I have tried are covered in Can you help with this MVC ViewModel issue?
This however does not appear to be the right approach.
You need a view model specifically tailored to the needs of this view. When defining your view models you shouldn't be thinking in terms of tables. SQL tables have absolutely no meaning in a view. Think in terms of what information you need to show and define your view models accordingly. Then you could use AutoMapper to convert between your real models and the view model you have defined.
So forget about all you said about tables and focus on the following sentence:
In the view I want to show a list of
retailers and with each retailer I
want to show the list of categories
applicable to them.
This sentence is actually very good as it explains exactly what you need. So once you know what you need go ahead and modelize it:
public class CategoryViewModel
{
public string Name { get; set; }
}
public class RetailerViewModel
{
public IEnumerable<CategoryViewModel> Categories { get; set; }
}
Now you strongly type your view to IEnumerable<RetailerViewModel>. From here it is easy-peasy to do what you want in the view:
showing a list of retailers with each retail having a list of associated categories.
this could be also helpful;
video from chris pels
It is simple just do what I say step by step.
add connection string into web.config file
select models from solution explorer and add 4 classes as following
1st class for first table "i have employ table which have 3 columns
public class Employ
{
[Key]
public int Emp_id { get; set; }
public string Emp_name { get; set; }
public string Emp_city { get; set; }
}
2nd class for my tempo table
public class tempo
{
[Key]
public int ID { get; set; }
public int Emp_Id { get; set; }
public string subject { get; set; }
public string hobby { get; set; }
}
Now I create a third class in model folder which contain value that i want from employ table and tempo table
public class Alladd
{
public int ID { get; set; }
public int Emp_Id { get; set; }
public string subject { get; set; }
public string hobby { get; set; }
public string Emp_name { get; set; }
public string Emp_city { get; set; }
}
and the final class is datacontext class
public class DataContext:DbContext
{
public DataContext() : base("DefaultConn")//connection string
{
}
public DbSet<Employ> Empdata { get; set; }
public DbSet<tempo> Tempdata { get; set; }
}
now go to the Home controller and add code as below
public ActionResult file()
{
// IList<tempo> tempi=new List<tempo>();
IEnumerable<Alladd> model = null;
// model = getVerifydetails(id);
// return View(objcpModel);
List<Alladd> verify = new List<Alladd>();
cn.Open();
if (cn.State == ConnectionState.Open)
{
string query = "select Employ.Emp_name,Employ.Emp_id,Employ.Emp_city,tempo.hobby,tempo.id,tempo.subject from Employ inner join tempo on Employ.Emp_id=tempo.Emp_id;";//joining two table
SqlCommand cmd=new SqlCommand(query,cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
verify.Add(new Alladd { Emp_name = dr[0].ToString(), Emp_Id= Convert.ToInt32(dr[1].ToString()), Emp_city = dr[2].ToString(), hobby = dr[3].ToString(),ID = Convert.ToInt32(dr[1].ToString()),subject= dr[4].ToString()});//filling values into Alladd class
}
cn.Close();
}
return View(verify);
}
now the final step is so simple
go to solution explorer
select views folder and left click on it and select add view
now name it as "file" which we give it into controller
check on create strongly type view
select model class from dropdown-> Alladd
select scaffold templet ->List
hit Add button
Now you're done
Happy coding...

Resources