How to get a relational entity-object by Linq-to-Entity? - c#

using (var dataContext = new realtydbEntities())
{
var user =
(
from aspnet_Roles rol in dataContext.aspnet_Roles.Include("aspnet_Users")
from aspnet_Users usr in rol.aspnet_Users
where rol.RoleId == roleID
select usr
);
return user.ToList();
}
I want use
usr.MemberShip.Email
MemberShip is a foreign table's foreign table.
aspnet_Roles->aspnet_Users->Membership.Email
but i got an error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
How can i include the membership object to the result??????

You will most probably need to include the aspnet_Membership table that hangs off the aspnet_User table as below:
using (var dataContext = new realtydbEntities())
{
var user =
(
from aspnet_Roles rol in dataContext.aspnet_Roles.Include("aspnet_Users")
from aspnet_Users usr in rol.aspnet_Users.Include("aspnet_Membership")
where rol.RoleId == roleID
select usr
);
return user.ToList();
}

Related

How to get two table value using Linq

I have two table one is Administrator table and another is Teacher table .
I want to display these both tables values in single Gridview .
I have make id as a primary key in Administrator table and make this tech_id as foreign key in Teacher table .
Now how to get these table values together in single gridview as shown in pic
Now please any body help me how to get these two value together using Linq .
I have try but I can't make any more
private void loadgri()
{
StudentDatabaseEntities empl = new StudentDatabaseEntities();
var query=from g in empl.Teachers
join m in empl.Administrators on g.id equals m.id
where m.username=="cs"
select new{
Name = g.username,
};
}
You don't need a join if you have already a navigation-property:
var query= from t in empl.Teachers
where t.Administrator.username == "cs"
select new { Teacher = t.username, Administrator = t.Administrator.username };
This is just an example, but you see that you can access all properties of both entities.
Don’t use Linq’s Join. Navigate!
To show all the teachers and their administrator, you don't have to use "join", you could just use the navigation property:
var query = from g in empl.Teachers
where g.Administrator.username=="cs"
select new {
Teacher_Id = g.Id,
Teacher_Name = g.username,
Administrator_Id = g.Id,
Administrator_Name = g.Administrator.username,
//etc...
};

From SQL server, extract a list of Users containing the list of all their bought application (mapping table)

Let Users be a database containing typical users data (name, email...) with an ID as primary key.
Let Applications be a database storing a list of applications (name, developer...) with an ID as primary key.
Let UsersApps be the mapping table between the two, using the primary key. UsersApps thus stores rows of ..., {102, user1_Id, appA_Id}, {103, userN_ID, appB_Id}, {104, user1_Id, appC_Id}, ...
And so on.
I want to retrieve a list of users data {name, email, List<Application> boughtApps}
I am struggling to find a LINQ request to do that and I am trying to do it in two steps, get a big table and then build each user's list of applications.
var q1 = from user in _dbContext.Users
join appUti in _dbContext.AppUsers on user.Id equals appUti.UsersId
join app in _dbContext.Applications on appUti.ApplicationId equals app.Id
orderby user.Id
select new UserDataWithApp { Id = user.Id, Name = user.Name, firstName= user.FirstName, Email = user.Email, App = app };
Then parse q1.toList() to build my required results list.
var qRes = q1.ToList();
int i = 0;
int j = 0;
while (i<qRes.Count())
{
listUsersWithApps[j] = qRes[i];
while (qRes[i].Id == listUsersWithApps[j].Id) // llist is ordered !!
{
listUsersWithApps[j].Apps.Add(qRes[i].Apps[0]);
i++;
}
j++;
}
Isn't there a better way ?
You can use navigation properties to allow the following:
var userApps = context.Users.Select(u => new UserWithApp(u.Name, u.Email, u.Applications))
Just add to following to User:
public virtual ICollection<Application> Applications { get; set; }
and to Application:
public virtual ICollection<Users> Users { get; set; }
So you can "navigate" between your entities and write to following query (just adapt your ordering and what user data to be seleted):
var userApps = from user in context.Users
select new UserDataWithApp { ..., BoughtApps = user.Applications }
See here for an example: http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
or another interesting blog: https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/

Acessing UserRoles table in aspnet identity via linq

So i can access the User table, but i need to do a further query within my linq statement to check to see if they have been added into a particular user role
var managers = (from a in db.Users
join b in db.**UserRoles** on a.Id equals b.Id
where a.IsManager == true select a).ToList();
I know you can access it via the html using User.IsInRole, but i really need to access it via my DB call
any help would be great
Given that you are using asp.net identity with code-first approach? you can access the users or Roles tables individually (db.Users/db.Roles). If you want to access roles for a user you could do db.Users.Roles. However, this would only return id's for your roles (there are no navigationproperty from here..)
To check for users in role by role-name, you could join user.Roles with db.Roles, and check the role name from db.Roles. Something like this:
using (var db = new ApplicationDbContext())
{
var user1 = new ApplicationUser { Email = "user1#test.com", UserName = "User #1"};
var user2 = new ApplicationUser { Email = "user2#test.com", UserName = "User #2 - No Roles" };
var role1 = new IdentityRole("SomeRole");
db.Users.Add(user1);
db.Users.Add(user2);
db.Roles.Add(role1);
db.SaveChanges();
user1.Roles.Add(new IdentityUserRole { RoleId = role1.Id });
db.SaveChanges();
var usersInRole = db.Users.Where(u =>
u.Roles.Join(db.Roles, usrRole => usrRole.RoleId,
role => role.Id, (usrRole, role) => role).Any(r => r.Name.Equals("SomeRole"))).ToList();}
Alternatively you could first fetch the Role and then check
var usersinRole = db.Users.Where(u => u.Roles.Any(r => r.RoleId.Equals(someRoleId)));
Depending on which version of you are using you should have some tables like this:
You will need to join to the users in roles table and the roles table.

Duplicate entries using ASP.NET MVC 4, Entity Framework & SQL Server

I inherited an ASP.NET MVC 4 app that is using Entity Framework and keep getting duplicate records on related tables. I haven't been able to figure out why this is happening and it only happens randomly.
The models are as such:
Company -> has many Users -> has many UserRoles
UserRoles references the Roles table which has a RoleId and Name.
It is duplicating entries in the Roles table. I have been trying to figure this out but am pretty new with EF and some of that.
UserRole.cs partial class:
public static bool UpdateUserRoles(int userId, List<int> roleIds)
{
using (var context = new ImageTrackerEntities())
{
var userRoles = context.UserRoles.Where(r => r.UserId == userId).ToList();
foreach (var role in userRoles)
{
// do not remove users from super admin role
context.Entry(role).State = EntityState.Deleted;
}
foreach (var id in roleIds)
{
var ur = new UserRole() {
RoleId = id,
UserId = userId
};
context.Entry(ur).State = EntityState.Added;
}
context.SaveChanges();
return true;
}
}
To notice whats happened more precisely , try to activate EF Log so you can see the SQL generated (If you are using EF6 (current version of course)). Something like this :
using (var context = new BlogContext())
{
//YOU NEED TO ADD THIS
context.Database.Log = Console.Write;
var blog = context.Blogs.First(b => b.Title == "One Unicorn");
blog.Posts.First().Title = "Green Eggs and Ham";
blog.Posts.Add(new Post { Title = "I do not like them!" });
context.SaveChanges();
}
This will generate the following output:
SELECT TOP (1)
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title]
FROM [dbo].[Blogs] AS [Extent1]
WHERE (N'One Unicorn' = [Extent1].[Title]) AND ([Extent1].[Title] IS NOT NULL)
-- Executing at 7/17/2015 10:55:41 AM -07:00
-- Completed in 4 ms with result: SqlDataReader

Problem in Inserting or Updating in many to many relationship EF4

Let's say have 3 tables:
Category
-------------
CategoryID int
Title text
Admin
------------
AdminID int
FullName text
Permission
------------
CategoryID int
AdminID int
AllowAccess bit
When i try to update changes to database i got following exception:
Unable to insert or update an entity because the principal end of the 'KiaNetModel.FK_Permissions_Admins' relationship is deleted.
WHY?
The function that update changes:
public static void SetPermissions(int[] cats, int userId, Entities context)
{
var premissions = from p in context.AdminPremissions where p.AdminID == userId select p;
// Clear all premissions...
foreach (var p in premissions)
{
p.AllowAccess = false;
}
foreach (var c in cats)
{
var es = from e in context.AdminPremissions where e.CategoryID == c && e.AdminID == userId select e;
// If any pre permission was found, set flag = true
if (es.Count() > 0)
es.First().AllowAccess = true;
// Otherwise add new one
else
context.AdminPremissions.AddObject(new AdminPremission() { AdminID = userId, CategoryID = c, AllowAccess = true });
}
}
It's an web application, and when user mark permissions, i could only determine which permissions are set, not all of them.
If you have any other idea, or better way please tell me.
I think relationship between tables Permission and Admin has been deleted from either Actual database or from Entity Model. It it is the case then u have to create that relationship again.
Generate "Admin" Table And "Permission" Drop And Create Script (With Data - If U Have Data On it).
Then Execute It, If U Have Relation Re Create It,
Ur Prb Must Be Solve.

Categories