Entity Framework navigating using navigation properties more than one level - c#

I have Entity model classes as follows
public partial class User
{
public User()
{
this.webpages_Roles = new HashSet<webpages_Roles>();
}
public int UserID { get; set; }
public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
}
.
public partial class webpages_Roles
{
public webpages_Roles()
{
this.Users = new HashSet<User>();
this.Roles_X_ApplicationModules =
new HashSet<Roles_X_ApplicationModules>();
}
public int RoleId { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Roles_X_ApplicationModules>
Roles_X_ApplicationModules { get; set; }
}
.
public partial class Roles_X_ApplicationModules
{
public long ID { get; set; }
public Nullable<int> ModuleID { get; set; }
public Nullable<int> RoleID { get; set; }
public Nullable<bool> ViewPermission { get; set; }
public virtual ApplicationModule ApplicationModule { get; set; }
public virtual webpages_Roles webpages_Roles { get; set; }
}
.and
public partial class ApplicationModule
{
public ApplicationModule()
{
this.Roles_X_ApplicationModules =
new HashSet<Roles_X_ApplicationModules>();
}
public int ModuleID { get; set; }
public virtual ICollection<Roles_X_ApplicationModules>
Roles_X_ApplicationModules { get; set; }
}
you can see User object has a navigation property to webpages_Roles which again has navigation property to Roles_X_ApplicationModules and which in turn navigates to ApplicationModule..
now I want to get all the ApplicationModule from User..how do I write query using navigation properties..
I tried something like this..
var appModules = user.webpages_Roles.SingleOrDefault()
.Roles_X_ApplicationModules.Where(z => z.ViewPermission == true)
.Select(x => x.ApplicationModule);
but problem with this is, it doesn't issue a single query to database. It splits the query to get the webpages_Roles at SingleOrDefault then another query to get the Roles_X_ApplicationModules based on the RoleId and at the end as many queries as Roles_X_ApplicationModules matching the condition to get the ApplicationModule.
How do I write the LINQ query so that a single sql query is issued to database?

You can use Include() to do this.
Example:
card = Cards.Include(l => l.DocumentLinks)
.Include(l => l.Charges.Select(ch => ch.DocumentLinks)
.SingleOrDefault(c=>c.Id==id);
This is for three linked Entities:
public class Card
{
public Guid Id{get;set;}
public virtual ICollection<DocumentLink> DocumentLinks{get;set;}
public virtual ICollection<Charge> Charges{get;set;}
}
public class Charge
{
...
public virtual ICollection<DocumentLink> DocumentLinks{get;set;}
}
public class DocumentLink
{
...
}

try this:
var appModules = from u in user
from w in u.webpages_Roles
from am in w.Roles_X_ApplicationModules
where am.ViewPermission == true
select am;
if you want eager loading then you just need to call ToList:
var appModules = (from u in user
from w in u.webpages_Roles
from am in w.Roles_X_ApplicationModules
where am.ViewPermission == true
select am).ToList();

Related

Filtering on the Collection Navigation property

I would like to filter my 'TranslationSet' entities, based on their 'Translations' Collection Navigation Property.
E.g.
If a 'Translation' has a 'LanguageId' of 5 (Italian), then the 'TranslationSet' that contains this 'Translation' should be removed from the result.
Here are my Entity classes:
public class Language
{
public int LanguageId { get; set; }
public string NationalLanguage { get; set; }
//Make table multi tenanted.
public int TenantId { get; set; }
public ApplicationTenant Tenant { get; set; }
public List<Translation> Translation { get; set; } = new List<Translation>();
}
public class Translation
{
public int TranslationId { get; set; }
public string TranslatedText { get; set; }
public int LanguageId { get; set; }
public Language Language { get; set; }
//Make table multi tenanted.
public int TenantId { get; set; }
public ApplicationTenant Tenant { get; set; }
public int TranslationSetId { get; set; }
public TranslationSet TranslationSet {get; set;}
}
public class TranslationSet
{
public int TranslationSetId { get; set; }
public int TenantId { get; set; }
public ApplicationTenant Tenant { get; set; }
public IEnumerable<Translation> Translations { get; set; }
}
Here is my attempt
From the image you can see that the query fails because a Translation exists with LanguageId of 5.
I have tried many many attempts to resolve this but I can't even get close the LINQ which returns my query correctly.
Please let me know if any further clarification is needed and thanks in advance to anybody who offers help.
My rule of the thumb that nearly always work is: start by querying the entities you want. That will prevent duplicates as you see in your query result. Then add predicates to filter the entities, using navigation properties. That will be:
var sets = TranslationSets // start the query here
.Where(ts => ts.Translations.All(t => t.LanguageId != 5)); // Filter
Or if you like this better:
var sets = TranslationSets // start the query here
.Where(ts => !ts.Translations.Any(t => t.LanguageId == 5)); // Filter
EF will translate both queries as WHERE NOT EXISTS.

WPF Entity Framework Foreign key won't load it's value in a DataGrid

I am using Entity Framework code first with fluent API I have an items table with foreign keys from users and units tables
but when I load the table to ObservableCollection then bind it to a datagrid the table normal column load it's data normally into the datagrid excpet for the foreign keys which show nothing but when i insert a break point to see the data inside the ObservableCollection I can see that every thing from Users and Units table is there
private void MainContentsWindow_ContentRendered(object sender, EventArgs e)
{
using (var db2 = new DataContext())
{
var AllItems2 = new ObservableCollection<Model.Items.Item>(db2.Items);
ItemsDataGrid.ItemsSource = AllItems2;
}
}
Users
public class User
{
public User()
{
Id = Guid.NewGuid();
IsActive = false;
}
public Guid Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public UserGroup Group { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<Items.Item> Items { get; set; } = new List<Items.Item>();
}
public enum UserGroup
{
Administrator = 1,
User,
Unknown
}
base
public class NormalBaseModel : CommonBase
{
public NormalBaseModel()
{
Id = new Guid();
CreateDate = DateTime.Now;
EditDate = null;
}
public Guid Id { get; set; }
public string Notes { get; set; }
public virtual User CreateBy { get; set; }
public DateTimeOffset? CreateDate { get; set; }
public virtual User EditBy { get; set; }
public DateTimeOffset? EditDate { get; set; }
}
items
public class Item : NormalBaseModel
{
public string NameAr { get; set; }
public string NameEn { get; set; }
public int? ManualId { get; set; }
public string Barcode { get; set; }
public byte?[] Image { get; set; }
public virtual Unit Unit { get; set; }
public string MadeIn { get; set; }
public bool IsSerail { get; set; }
public bool IsExpire{ get; set; }
}
Here is a test project on Github
https://github.com/ahmedpiosol/psychic-parakeet.git
https://imgur.com/a/zimd4
When you load your items via EF it needs to create new instances of User and Item. Behind the scenes, EF will call the constructor for each new instance. Your problem is in your constructors:
public User()
{
Id = Guid.NewGuid(); // <- here
}
Your constructor reassigns a new ID each time an instance is created, this will break the referential integrity and cause all sorts of other problems.
Your code doesn't know the difference between creating a new User and recreating a User instance from the database.
I suggest removing the assignments from inside your constructor and placing this either in a static Create method or place wherever you are creating a new User or Item.
p.s. WPF is irrelevant to your problem here.
Fluent API needs to specify foreign key in code, something like
modelBuilder.Entity<Items>()
.HasRequired(o => o.User)
.WithMany(c => c.Items)
.HasForeignKey(o => o.UserId);

Entity Framework query with simple join

I am using Entity Framework 6 in a project and am having trouble creating a query.
Say my classes are defined like:
public class MyContext : DbContext
{
public MyContext(string connectionString) : base(connectionString)
{
}
public DbSet<EntityXXX> XXXSet { get; set; }
public DbSet<EntityYYY> YYYSet { get; set; }
}
public class EntityXXX
{
public string XXXName { get; set; }
public int id { get; set; }
public int YYYid { get; set; }
}
public class EntityYYY
{
public string YYYName { get; set; }
public int id { get; set; }
}
The YYYid property of EntityXXX is the 'id' of the EntityYYY instance that it relates to.
I want to be able to fill a Grid with rows where the first Column is XXXName and the second column is YYYName (from its related EntityYYY), but I can't see how to do this?
I'm sure it's really simple, but I'm new to EF.
You need to put a virtual navigation property on your EntityXXX
public virtual EntityYYY YYY { get; set; }
Then you can do a projection:
db.XXXSet
.Select(x => new { x.XXXName, YYYName = x.YYY.YYYName })
.ToList();
Which will get you the list you need.

EntityFramework: How to load List of objects from database?

I have two entities:
public class Booking
{
[Key]
public int Id { get; set; }
public int RoomId { get; set; }
[ForeignKey("RoomId")]
public Room Room { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DocumentNumber { get; set; }
public string ContactPhone { get; set; }
}
public class Room
{
[Key]
public int RoomId { get; set; }
public int Number { get; set; }
public int Size { get; set; }
public bool HasBalcony { get; set; }
public int Beds_1 { get; set; }
public int Beds_2 { get; set; }
public double DayPrice { get; set; }
public List<Booking> Bookings { get; set; }
...
public int BookingsCount()
{
return Bookings.Count;
}
public bool IsFree(DateTime dateTime)
{
MessageBox.Show(BookingsCount().ToString());
return true;
}
}
and DbContext:
public class HotelContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Room> Rooms { get; set; }
public DbSet<Booking> Bookings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Room)
.WithMany(r => r.Bookings)
.HasForeignKey(b => b.RoomId);
}
}
When MessageBox.Show is called I'm getting exception: An unhandled exception of type 'System.NullReferenceException' occurred in Hotel.exe
When I'm trying to access Room::Bookings, the list is always null. There is one row in Bookings table and multiple rows in Rooms table.
How can I load all of Bookings into Room object?
Depends where you are in the learning curve, however some things stand out
Firstly
You either want to create a relationship via FluentApi or Annotations, not both
Ie. you have this on your Room entity
[ForeignKey("RoomId")]
And this in fluent
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Room)
.WithMany(r => r.Bookings)
.HasForeignKey(b => b.RoomId);
You need to pick one or the other, otherwise you may end-up with multiple Ids in your Booking i.e RoomId and Room_Id
Secondly
If you want to be able to Lazy Load bookings you need to make Bookings collection Virtual
public virtual List<Booking> Bookings { get; set; }
Lastly
To access your data (presuming your connection string is correct)
using(var db = new HoteContext())
{
var rooms = db.Rooms.Include(x => x.Bookings).ToList();
}
Note : Although EF Lazy loads relationships, you might want to make sure you have included the Room->Booking relationship
Consider the following code.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (MyDbContext dbContext = new MyDbContext())
{
dbContext.Departments.Add(new Department()
{
Name = "Some Department1",
Employees=new List<Employee>()
{
new Employee() { Name = "John Doe" }
}
});
dbContext.SaveChanges();
var department = dbContext.Departments.FirstOrDefault(d => d.Name == "Some Department1");
if (department.Employees != null)
{
foreach (var item in department.Employees)
{
Console.WriteLine(item.Name);
}
}
}
}
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
}
}
If you have the code in above way, the control will not go into if condition, because department.Employees is null. Now, change the Department entity as follows.
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Employee> Employees { get; set; }
}
And now you should be able to see control go into if condition and outputs the employees name.
That is called Lazy Loading.
If you want to eagerly load, you don't have to put virtual to the property. You can Include the properties as follows.
var department = dbContext.Departments.Include(d => d.Employees).FirstOrDefault(d => d.Name == "Some Department1");
Now you can see the employees names are getting outputted.
You will absolutely run into performance trouble with your design here.
The temptation with EF is to completely map your object model to the DB and have EF do all the magic for you behind the scenes. But you need to think about it in terms of only getting specifically what you need from the db at any point in time. Otherwise you will get all kinds of cartesian product issues. I highly suggest you get yourself a copy of Hibernating Rhino's EF Profiler or similar so you can analyze your code statically and at runtime for EF performance issues (and see what SQL it is generating). For this what you want is a purpose built call to the DB to get the count. Otherwise what will happen is you will pull the entire table of Bookings and then have C# give you the count. That only makes sense if you want to do something with the whole list. Two options would be:
1) Create a VIEW against the Bookings table and map that to EF. The view would look something like SELECT ROOMS.ROOMID, COUNT(*) - you map this view to your model and voila now you have a list of counts by room (id) and you can use them individually or sum it up to get your total count for all rooms. If you have 1,000 bookings in 10 rooms, you are getting back only 10 rows from the DB. Whereas with your design, you are pulling back all 1,000 bookings with all their fields and then filtering down in C#. Bad juju.
2) The architecturally and conceptually simpler approach is going to be to do a direct query as such (obviously this returns only a single int from the db):
public int BookingsCount()
{
int count = 0;
try
{
using (var context = new HotelContext())
{
var sql ="SELECT COUNT(*) FROM Bookings WHERE ROOMID=" + this.RoomId;
count = context.Database.SqlQuery<int>(sql).First();
}
} catch (Exception ex)
{
// Log your error, count will be 0 by default
}
return count;
}
A simple solution would be making the Bookings property virtual.
public class Room
{
[Key]
public int RoomId { get; set; }
public int Number { get; set; }
public int Size { get; set; }
public bool HasBalcony { get; set; }
public int Beds_1 { get; set; }
public int Beds_2 { get; set; }
public double DayPrice { get; set; }
public virtual List<Booking> Bookings { get; set; }
}
More information on Entity Framework Loading Related Entities,
https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

Linq query to include items with on a join object

I'm trying to get a collection of objects using a Linq query that would include child objects. I can do an include on the main table and get results. But if I do an include on one of the tables I join to, I do not get the object that should be returned by the include.
Here are my models:
public class RequestReviewViewModel
{
public Guid RequestId { get; set; }
public Guid ResourceToReviewId { get; set; }
public Guid ReviewRequiredId { get; set; }
public ReviewRequired ReviewRequired { get; set; }
}
public class Required : BaseEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid RequiredId { get; set; }
[Display(Name = "Review Name")]
public int ReviewNameId { get; set; }
[ForeignKey("ReviewNameId")]
public ReviewName ReviewName { get; set; }
}
Here's the linq query I'm trying. The line Required.Include(revr => revr.ReviewName) doesn't seem to do anything:
var requests = (from req in Request.Include(rr => rr.Resource)
join revreq in Required.Include(revr => revr.ReviewName)
on req.ReviewRequiredId equals revreq.RequiredId
where req.IsActive
select new RequestReviewViewModel
{
RequestId = req.RequestId,
ResourceToReviewId = req.ResourceToReviewId,
ReviewRequiredId = req.ReviewRequiredId,
Required = revreq
};
requests.FirstOrDefault().Required.ReviewName.Dump();
While requests.FirstOrDefault().Required.ReviewNameId has a value, the ReviewName object is null. The relationship is in the database, and was created by Code First.
Your ReviewName is not declared virtual which enables eager/lazy loading (and automatic change-tracking to be complete). Add virtual and it should work:
public virtual ReviewName ReviewName { get; set; }

Categories