ASP.NET MVC model from db - c#

I created my model from DB in which I have tables Users, Roles and UsersInRoles which is an intermediary table between the first 2.
My question is how do I take specific users where Roles = something since the table UsersInRoles is not added to the model?
public partial class Role
{
public Role()
{
this.Users = new HashSet<User>();
}
public int RoleID { get; set; }
public string RoleName { get; set; }
public string RoleDescription { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public partial class User
{
public User()
{
this.Roles = new HashSet<Role>();
}
public int UserID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public ActionResult Index()
{
var users = db.Users;
return View(users.ToList());
}

I believe this will work...
var usersInRole = db.Users.Where(x => x.Roles.Any(y => y.RoleId == roleid));

I admittedly haven't had much experience with HashSets, but is there any reason a simple Linq query wouldn't work?
var requestedUsers = from UsersInRoles
in db.Users
where UsersInRoles.Roles.Contains(DesiredRoleHere)
select UsersInRoles;

Related

How to use Linking Table in Entity Framework

I've been trying to puzzle out how to use entity framework to return a query like so
{
UserID: 1,
Roles: ["RoleOne","RoleTwo","RoleThree"]
}
Where my tables are as such:
public class User
{
public int? ID { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
}
public class UserRoles
{
public int ID { get; set; }
public int UserID{ get; set; }
public int RoleID { get; set; }
}
public class Roles
{
public int ID { get; set; }
public string? Name { get; set; }
}
I've tried joins, and looked into creating a relationship in the classes, as well as trying to figure out groupBy, but all with no luck.
If I'm missing something obvious please let me know! Thanks!
Your response model should be like this:
public class RespModel
{
public int UserID { get; set; }
public List<string> Roles { get; set; }
}
And your query could be like this:
var query = from userRolesRec in _context.UserRoles
join user in _context.User on userRolesRec.UserID equals user.ID ?? 0
select new RespModel
{
UserID = user.ID,
Roles = (from roles in _context.Roles
where userRolesRec.RoleID == roles.ID
select roles.Name).ToList()
}

Mapping lists with Automapper

I am using code first migrations for creating entities. My entities look like that:
public class User
{
private string userWholeName = string.Empty;
private ICollection<UsersInRoles> usersInRoles;
public User()
{
this.UserId = Guid.NewGuid();
this.usersInRoles = new System.Collections.Generic.HashSet<UsersInRoles>();
}
[Key]
public Guid UserId { get; set; }
//TODO: check for resource names and for all models
[Required(AllowEmptyStrings = false, ErrorMessage = null)]
public string UserName { get; set; }
[Required(AllowEmptyStrings = false)]
[MaxLength(30)]
public string Password { get; set; }
public virtual ICollection<UsersInRoles> UsersInRoles
{
get { return this.usersInRoles; }
set { this.usersInRoles = value; }
}
}
My UsersInRolesClass:
public class UsersInRoles
{
public UsersInRoles()
{
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UsersInRolesId { get; set; }
public Guid UserId { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
public virtual User User { get; set; }
}
My Role class:
public class Role : Interfaces.IRole
{
private ICollection<UsersInRoles> usersInRoles;
public Role()
{
this.usersInRoles = new HashSet<UsersInRoles>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
[Required]
public string RoleName { get; set; }
public string RoleDescription { get; set; }
public virtual ICollection<UsersInRoles> UsersInRoles
{
get
{
return this.usersInRoles;
}
set
{
this.usersInRoles = value;
}
}
}
So those are my db entities. I am trying to map them to:
public class UserDTO
{
//other properties same as in User entity
IList<RoleDTO> Roles { get; set; }
}
public class RoleDTO
{
int RoleId { get; set; }
string RoleName { get; set; }
}
Every property is mapped, but Roles are not. I am trying this:
Mapper.Initialize(cfg => cfg.CreateMap<UserDTO, User>().ForMember(dest => dest.UsersInRoles, opt => opt.ResolveUsing(c=>c.Roles.Select(f=>new UsersInRoles() { Role = new Role() { RoleId = f.RoleId,RoleName = f.RoleName}, RoleId = f.RoleId,UserId = c.UserId }))));
Any Ideas ?

ASP.net MVC: Display Results For A Specific User

I'm using ASP.net MVC with Individual User Accounts. I want a page that shows all database records where the field "user" equals the email address of the account. I used scaffolding to create everything, I just need to add a where clause somehow that only shows records for the specific user. I attempted that in the controller below. It compiles, and Exhibit5/Index/ prompts user with login screen as expected. However, upon clicking LogIn, I get a network path not found error.
Model:
public partial class Exhibit5
{
public int ID { get; set; }
public string User { get; set; }
public string Name { get; set; }
public Nullable<int> EmployeeID { get; set; }
public string ProposedTitle { get; set; }
public string Department { get; set; }
public Nullable<decimal> AnnualizedSalary { get; set; }
public string PayGrade { get; set; }
public Nullable<decimal> MktPay { get; set; }
public Nullable<decimal> RangeMin { get; set; }
public Nullable<decimal> RangeMid { get; set; }
public Nullable<decimal> RangeMax { get; set; }
public Nullable<decimal> RangePen { get; set; }
public Nullable<decimal> CompaRatio { get; set; }
public Nullable<decimal> BelowMin { get; set; }
public Nullable<decimal> AboveMax { get; set; }
}
}
Controller:
public class Exhibit5Controller : Controller
{
private WebApplication1Context db = new WebApplication1Context();
[Authorize]
// GET: Exhibit5
public ActionResult Index()
{
var ex5 = db.Exhibit5.Where(d => d.User == User.Identity.GetUserName()).ToList();
return View(ex5);
}
It should be:
var userName = User.Identity.GetUserName();
var ex5 = db.Exhibit5.Where(u => u.User == userName )
.Select(y => y.User);
Quick-fix:
public ActionResult Index()
{
var userName = User.Identity.GetUserName();
var ex5 = db.Exhibit5.Where(d => d.User == userName).ToList();
return View(ex5);
}
The reason User.Identity.GetUserName() doesn't work inside Where because Entity Framework needs to convert your Where code into SQL Queries and it doesn't know how to do User.Identity.GetUserName(). By pulling it out of makes Entity Framework do (kind of) this:
SELECT * FROM Exhibit5 WHERE User = <User Name>

How to map a List in Entity Framework?

I have two classes: Role and RoleViewModel.
Role class
public partial class Role
{
public Role()
{
this.Users = new HashSet<User>();
}
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
}
RoleViewModel class
public class RoleViewModel
{
public RoleViewModel()
{
this.Users = new HashSet<UserViewModel>();
}
public int RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<UserViewModel> Users { get; set; }
}
Now, I am trying to fetch a list of Role from database and map it to a list of RoleViewModel.
public static List<RoleViewModel> GetRolesService()
{
List<Role> roles =MainRepository.GetUserRoles();
var rolesVM = Mapper.Map<List<Role>, List<RoleViewModel>>(roles);
return rolesVM;
}
The problem is that rolesVM list always have Count=0, and I don't know why.
Thanks in advance!.
One solution is to ignore nested dependencies.
Mapper.CreateMap<Role, RoleViewModel>().ForMember(c=>c.Users,option=>option.Ignore());

Add value to one object in EF

I have a function:
public void Add(User user)
{
var id = WebSecurity.CurrentUserId;
//add id to FK CUserID
context.User.Add(user);
}
I'm adding user data to database. How to add id value to CUserID?
public class User
{
[key]
public int UserID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string E-mail { get; set; }
public UserProfile CUserID { get; set; }
}
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CUserId { get; set; }
public string UserName { get; set; }
}
EDIT:
If I try do:
user.CUserId = id;
I get an error:
Cannot implicitly convert type 'int' to 'Project.Models.UserProfile'
Change the User class:
public class User
{
[key]
int UserID { get; set; }
string Name { get; set; }
string Surname { get; set; }
string E-mail { get; set; }
[ForeignKey("UserProfile)]
int CUserID { get; set; }
virtual UserProfile UserProfile { get; set; ]
}
Now you can set the ID value and entity framework will get the matching UserProfile when you save changes.
Going on what you've described in your question, try this:
public void Add(User user)
{
using (var context = new MyDbContext())
{
var currentUser = context.UserProfile.Single(
u => u.UserName == System.Web.HttpContext.Current.User.Identity.Name);
var newUser = new User();
newUser.Name = user.Name;
newUser.Surname = user.Surname;
newUser.Email = user.Email;
newUser.CUserID = currentUser.CUserId;
context.User.Add(newUser);
context.SaveChanges();
}
}

Categories

Resources