Checking if navigation property is null Entity Framework - entity-framework

I have a model which contains a User. Each user must have a Person record. A person record may or may not have an Address record.
When I fetch the currently logged in User's address I am currently using the following which to me seems incredibly messy. Is there a better way to do this?
public Address GetAddress()
{
using (eziTraceEntities db = new eziTraceEntities())
{
if (db.Users.Where(u => u.ID == Globals.UserID).FirstOrDefault().Person.Address != null)
return db.Users.Where(u => u.ID == Globals.UserID).FirstOrDefault().Person.Address;
else
return new Address();
}
}
Thanks!

You can use the null coalesce operator:
using (eziTraceEntities db = new eziTraceEntities())
{
return db.Users.Where(u => u.ID == Globals.UserID).FirstOrDefault().Person.Address ?? new Address();
}

Related

EF Core 2.1 Updating related entites query efficiency

I'm having a student model in which i have list of phone numbers and addresses.When i update the student the related data(phone and address) needs to be updated. I have written a PUT action in my student controller for that. It works fine, but I'm concerned about the efficiency of the query. Please check the code and suggest me improvisation if any. Thanks
public async Task<IActionResult> Put(long id, [FromBody] Student student)
{
var p = await _Context.Students
.Include(t => t.PhoneNumbers)
.Include(t => t.Addresses)
.SingleOrDefaultAsync(t => t.Id == id);
if (p == null)
{
return NotFound();
}
_Context.Entry(p).CurrentValues.SetValues(student);
#region PhoneNumber
var existingPhoneNumbers = p.PhoneNumbers.ToList();
foreach (var existingPhone in existingPhoneNumbers)
{
var phoneNumber = student.PhoneNumbers.SingleOrDefault(i => i.Id == existingPhone.Id);
if (phoneNumber != null)
_Context.Entry(existingPhone).CurrentValues.SetValues(phoneNumber);
else
_Context.Remove(existingPhone);
}
// add the new items
foreach (var phoneNumber in student.PhoneNumbers)
{
if (existingPhoneNumbers.All(i => i.Id != phoneNumber.Id))
{
p.PhoneNumbers.Add(phoneNumber);
}
}
#endregion
#region Address
var existingAddresses = p.Addresses.ToList();
foreach (var existingAddress in existingAddresses)
{
var address = student.Addresses.SingleOrDefault(i => i.Id == existingAddress.Id);
if (address != null)
_Context.Entry(existingAddress).CurrentValues.SetValues(address);
else
_Context.Remove(existingAddress);
}
// add the new items
foreach (var address in student.Addresses)
{
if (existingAddresses.All(i => i.Id != address.Id))
{
p.Addresses.Add(address);
}
}
#endregion
await _Context.SaveChangesAsync();
return NoContent();
}
Searching over small in-memory collections is not normally something you would worry about. So if a Student has dozens or hundreds of addresses, the repeated lookups are not going to be significant, especially compared with the time required to write to the database.
If you did want to optimize, you can copy the students Addresses to a Dictionary. Like this:
var existingAddresses = p.Addresses.ToList();
var studentAddresses = student.Addresses.ToDictionary(i => i.Id);
foreach (var existingAddress in existingAddresses)
{
if (studentAddresses.TryGetValue(existingAddress.Id, out Address address))
{
_Context.Entry(existingAddress).CurrentValues.SetValues(address);
}
else
{
_Context.Remove(existingAddress);
}
}
A query over an in-memory collection like this:
var address = student.Addresses.SingleOrDefault(i => i.Id == existingAddress.Id);
Will simply iterate all the student.Addresses comparint the Ids. A Dictionary<> acts like an index, providing very fast lookups.

how to get list of one entity set from another entity set in a many to many relationship

1I am working with controller code in MVC.
I have the follow code working where the are related entities priority list based on teams:
public JsonResult GetPrioritiesByTeam(int id)
{
List<Priority> priorities = new List<Priority>();
if (id > 0)
{
priorities = db.Priorities.Where(p => p.Team == id ).ToList();
}
else
{
priorities.Insert(0, new Priority { Id = 0, PriorityDescription = "--Select a Team first--" });
}
var result = (from r in priorities
select new
{
id = r.Id,
name = r.PriorityDescription
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
The statement
priorities = db.Priorities.Where(p => p.Team == id
does get me the list of priorities based on the team passed in by the parameter id.
I am now try to achieve the same successful result with another entity that is related to team- an entity called 'members'. However the relationship is not a one to many. Its a many to many- so I have an intermediate entity call 'teammembers'.
The Team is still the entity driving the choice. When the team is chosen, I need it to give me all the team member entries in teammembers, and then I need similar to the priorities code above, give me a members list which is based on the teammembers identified based on the team selected.
I think based on the code provided the else clause would be similar coding along with the var result coding.
I just cant seem to get the coding right for the clause in the condition for id >0.
How do I write that clause for the many to many so as to get the list of members for the team through teammembers?
You can assume entity team is Id and TeamDescription, entity Member is Id and MemberName, and entity teammember is an ID,and teamId and MemberId -just a straightforward many to many.
Been trying with LINQ method syntax and LINQ query syntax but cant get it working.
Thanks for any help you can provide
New code would look like the following except i need working id>0 clause:
public JsonResult GetMembersByTeam(int id)
{
List<Member> members = new List<Member>();
if (id > 0)
{
**members = Members.Where(needed clause).ToList();**
}
else
{
members.Insert(0, new Member { Id = 0, MemberFullName = "--Select a Team first--" });
}
var result = (from m in members
select new
{
id = m.Id,
name = m.MemberFullName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Entity Diagram
Current code with suggested changes
public JsonResult GetMembersByTeam(int id)
{
List<Member> members = new List<Member>();
if (id > 0)
{
//members = db.Teams.Where(p => p.Id == id)
// .SelectMany(e => e.TeamMembers)
// .Select(e => e.Member)
// .ToList();
members = db.TeamMembers.Where(p => p.Team == id)
.Select(e => e.Member)
.ToList();
}
else
{
members.Insert(0, new Member { Id = 0, MemberFullName = "--Select a Team first--" });
}
var result = (from m in members
select new
{
id = m.Id,
name = m.MemberFullName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
results in error :
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List,ManageHR5.model.Member>'
try this:
members = db.TeamMembers.Where(p => p.Team == id )
.Select(e => e.Member1)
.ToList();

How to access Related Data built By the EF

Similar to the simple Membership UserProfiles to Roles in the Table UserInRoles
I have created a Relationship between UserProfiles to Clients in the table UserInClients with this code
modelBuilder.Entity<UserProfiles>()
.HasMany<dbClient>(r => r.Clients)
.WithMany(u => u.UserProfiles)
.Map(m =>
{
m.ToTable("webpages_UsersInClients");
m.MapLeftKey("ClientId");
m.MapRightKey("UserId");
});
My UserProfiles has an public virtual ICollection<dbClient> Clients { get; set; } and my Clients has an public virtual ICollection<UserProfiles> UserProfiles { get; set; }
If you need to see the Models let me know i can post them
In the model and view i would like to
Display all Clients ( Distinct ) and show how many users have access to that client
Create a View that only shows clients a Currently logged in user is allowed to view.
I thought it was as easy as accessing the Properties of my models Clients.ClientID, i have been trying things like Clients.ClientID.select(u=>u.UserId == clientid) but i knew better and know it does not and will not work.
My other thoughts were creating a model with CliendID and UserID in it ( like the table it created ) so i can use a join in my controller to find the right values??
In the end what i'm trying to accomlish is to populate a KendoUI CascadingDropDownList with this line in my GetCascadeClients JsonResult
return Json(db.Clients.Select(c => new { ClientID = c.ClientID, ClientName = c.Client }), JsonRequestBehavior.AllowGet);
My question is, when I'm in my Controller, how do I access this table built by Entity Framework?
EDIT:
SOLUTION QUERY Pieced together by both answers
return Json(db.Clients
.Include(c => c.UserProfiles)
.Where(c => c.UserProfiles.`Any(up => up.UserName == User.Identity.Name))`
.Select(c => new
{
ClientID = c.ClientID,
ClientName = c.Client,
UserCount = c.UserProfiles.Count()
}),
JsonRequestBehavior.AllowGet);
try something like:
return JSON (db.Clients
.Include(c => c.UserProfiles)
.Where(c => c.UserProfiles.UserId == loggedInUserId)
.Select( c => new {
ClientId = c.ClientID,
ClientName = c.Client,
UserCount = c.UserProfiles.Count()}),
JsonRequestBehavior.AllowGet);
the .Include() extension will make sure that you pull all the UserProfiles along with the Clients, allowing you to use that table for filtering, record counts, etc... that .Where clause might need some work actually, but this should be a solid start.
This is more of a LINQ question really:
db.Clients
.Where(c => c.UserProfiles.Any(up => up.UserId == loggedInUserId))
.Select(c => new {
ClientId = c.ClientID,
ClientName = c.Client + " (" + c.UserProfiles.Count() + ")"
})
Due to the fact that it will convert the above into SQL calls, I had to use string concatenation, as if you try to use a nice String.Format("{0} ({1})", c.Client, c.UserProfiles.Count()) it will complain about being unable to translate that to SQL.
The other options is to do a 2-pass query, materializing the data before doing extra formatting:
db.Clients
.Where(c => c.UserProfiles.Any(up => up.UserId == loggedInUserId))
.Select(c => new {
ClientId = c.ClientID,
ClientName = c.Client,
ProfileCount = c.UserProfiles.Count()
})
// this forces SQL to execute
.ToList()
// now we're working on an in-memory list
.Select(anon => new {
anon.ClientId,
ClientName = String.Format("{0} ({1})", anon.ClientName, anon.ProfileCount)
})

EF 4.1 DBContext - Apply filter loading related entities

I'm using EF 4.1 DBContext API, and I'm trying to load a parent entity named User and then explicitly load related Project entities using a .Where(x => x.IsEnabled) filter:
I found a suggested approach here under "Applying filters when explicitly loading related entities". But I cannot figure out why user.Projects is not being populated. Using SQL Profiler, I have verified I'm querying Projects and returning the data. But it's not being loaded into my user object.
Any thoughts?
Here is my code:
public User GetUser(string userName)
{
try
{
using (var context = new Entities())
{
var user = context.Users.FirstOrDefault(x => string.Compare(x.UserName, userName, true) == 0);
context.Entry(user).Collection(x => x.Projects).Query().Where(x => x.IsEnabled).Load();
//TODO: I expect user.Projects.Count() > 0.
}
}
catch (Exception ex)
{
LogWrapper.DumpException(ex);
}
return null;
}
User.projects = context.projects.select(x => x.user).where(x => x.isenabled);
Came across this problem recently, this is what I did. Hope you find it useful.
var query = context.User.Where(x => x.UserName == userName)
.Include(x => x.Projects.All(p => p.IsEnabled == true))
var data = query.ToList();

LINQ to Entity: How to include a conditional where condition

I'm new to EntityFramework and came across a problem with an unsupported function used in the Query.
Therefore I hope the community might help to find a elegant way.
The query tries to find a user based on the username and/or the windows username.
[Flags]
public enum IdentifierType
{
Username = 1,
Windows = 2,
Any = Username | Windows,
}
The following code throws an NotSupportedException because the Enum.HasFlag is cannot be translated into a store expression.
public User GetUser(IdentifierType type, string identifier, bool loadRelations = false)
{
using (var context = contextFactory.Invoke())
{
var user = context.Users.FirstOrDefault(u => u.Username == identifier && type.HasFlag(IdentifierType.Username)
|| u.WindowsUsername == identifier && type.HasFlag(IdentifierType.Windows));
return user;
}
}
If I rewrite the query the old Fashion way, the Query works but the boolean logic is executed in the DB:
public User GetUser(IdentifierType type, string identifier, bool loadRelations = false)
{
using (var context = contextFactory.Invoke())
{
var user = context.Users.FirstOrDefault(u => u.Username == identifier && (type & IdentifierType.Username) == IdentifierType.Username
|| u.WindowsUsername == identifier && (type & IdentifierType.Windows) == IdentifierType.Windows);
return user;
}
}
WHERE ((Username = #username) AND (1 = (3 & (1)))) OR (WindowsUsername
= #windowsusername) AND (2 = (3 & (2))))
How can I force the framework to evaluate the boolean logic before it is sent to the DB, so the binary operation is not done at DB Level?
Any ideas much appreciated!
for example:
public User GetUser(IdentifierType type, string identifier, bool loadRelations = false)
{
using (var context = contextFactory.Invoke())
{
IdentifierType tw = type & IdentifierType.Windows;
IdentifierType tu = type & IdentifierType.Username;
var user = context.Users.FirstOrDefault(u => u.Username == identifier && tu == IdentifierType.Username
|| u.WindowsUsername == identifier && tw == IdentifierType.Windows);
return user;
}
}
But I hope and believe that the database server detect that 1 = (3 & (1)) is a constant
Here you go (I've converted my code to yours so may not be syntactically 100%) ...
public User GetUser(IdentifierType type, string identifier, bool loadRelations = false)
{
using (var context = contextFactory.Invoke())
{
var user = context.Users.FirstOrDefault(u => u.Username == ((type.HasFlag(IdentifierType.Username)) ? identifier : u.Username) &&
&& u.WindowsUsername == ((type.HasFlag(IdentifierType.Username)) ? identifier : u.WindowsUsername);
return user;
}
}
Sorry, I've realized that the question did not point out the effective problem. After reading more about that, I had to rewrite the question and finally got a great answer from Gert Arnold, see here.
The LINQKit provides powerful extensions like the PredicateBuilder to cover dynamic queries with OR conditions.