ASP.net MVC: Display Results For A Specific User - c#

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>

Related

Is there a way to Ignore specific property in asp.net core Include function from many to many relationship

I am working on Asp.net core 5 Web-api, I am using many to many relationship between User entity and Permission entity, and I need to load users permission from the database using eager loading but the data is returning a looped information including users full information but I only load the permissions. I am using a Dto to return the Json data. Here is my models and my code
Permission Model
public class Permission
{
public int Id { get; set; }
public string ClaimName { get; set; }
public IList<UserPermission> UserPermissions { get; set; }
}
UserPermission model
public class UserPermission
{
public int UserId { get; set; }
public AppUser AppUser { get; set; }
public int PermissionId { get; set; }
public Permission Permission { get; set; }
}
User model
public class AppUser
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Photo> Photos { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public DateTime LastActive { get; set; }
public IList<UserPermission> UserPermissions { get; set; }
public bool Status { get; set; }
}
My user Dto
public class UserDto
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Photo> Photos { get; set; }
public ICollection<UserPermission> UserPermissions { get; set; }
public string Token { get; set; }
}
My function
var sss = _context.UserPermissions
.Include(l => l.Permission)
.Where(v => v.UserId == user.Id)
.ToList();
Use [JsonIgnore] on the properties that we want to exclude.
note that we should use "using Newtonsoft.Json" name space not using "System.Text.Json.Serialization"

.NET Core Entitiy Framework Get Mutiple Table

Sql Tables Here
public partial class Users
{
public Users()
{
UsersRelationFollower = new HashSet<UsersRelation>();
UsersRelationFollowing = new HashSet<UsersRelation>();
Vote = new HashSet<Vote>();
VoteRating = new HashSet<VoteRating>();
}
public string Id { get; set; }
public string UserType { get; set; }
public string UserName { get; set; }
public string Mail { get; set; }
public string ImageUrl { get; set; }
public DateTime CreationDate { get; set; }
public DateTime? ModifyDate { get; set; }
public bool State { get; set; }
public virtual UserPasswords UserPasswords { get; set; }
public virtual CorporateProperty CorporateProperty { get; set; }
public virtual UserProperty UserProperty { get; set; }
public virtual ICollection<UsersRelation> UsersRelationFollower { get; set; }
public virtual ICollection<UsersRelation> UsersRelationFollowing { get; set; }
public virtual ICollection<Vote> Vote { get; set; }
public virtual ICollection<VoteRating> VoteRating { get; set; }
}
public partial class UserProperty
{
public string Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime BirthDay { get; set; }
public string Gender { get; set; }
public string Locale { get; set; }
public string PhoneNumber { get; set; }
public bool State { get; set; }
public virtual Users IdNavigation { get; set; }
}
public partial class CorporateProperty
{
public string Id { get; set; }
public string OrganisationName { get; set; }
public string Website { get; set; }
public bool State { get; set; }
public virtual Users IdNavigation { get; set; }
}
UserControllerClass
// GET: api/Users/5
[HttpGet("{id}")]
public async Task<IActionResult> GetUsers([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var users = await _context.Users.SingleOrDefaultAsync(m => m.Id == id);
if (users == null)
{
return NotFound();
}
return Ok(users);
}
My problem is exactly this; User information is coming but the password and property table information is not coming.
How to modify the following line solves my problem?
var users = await _context.Users.SingleOrDefaultAsync(m => m.Id == id);
based on your code this would also hydrate your CorporateProperty & UseProperty objects, etc.
var user = await _context.Users.Include(user => user.UserProperty).Include
(user => user.CorporateProperty).SingleOrDefaultAsync(user => user.Id == id);
lazy loading doesn't exist yet so you have Eager Loading to play with for now.
Surprised you didn't roll with Identity since this all of this would have been taken care for you especially Passwords... Hope you aren't rolling your own hash for that..
Just add in the custom class / collection objects you need.
you can also check out this link
https://learn.microsoft.com/en-us/ef/core/querying/related-data

Getting a list of conversations with Entity Framework and linq

I am looking for a good way of getting a list of recent conversations.
I have made an inbox ui, where I am looking to implement a proper way of getting a list of conversations.
I have the following tables set up, with a relation to the Message table
public class Message
{
public int Id { get; set; }
public string Content { get; set; }
public string UserId { get; set; }
public ApplicationUser User { get; set; }
public DateTime CreateDate { get; set; }
public List<MessageReceived> MessagesReceived { get; set; }
public List<MessageSent> MessagesSent { get; set; }
}
public class MessageReceived
{
public int Id { get; set; }
public int MessageId { get; set; }
public virtual Message Message { get; set; }
public string FromUserId { get; set; }
public ApplicationUser FromUser { get; set; }
public string ToUserId { get; set; }
public ApplicationUser ToUser { get; set; }
public DateTime DateRecieved { get; set; }
public DateTime DateRead { get; set; }
public bool Deleted { get; set; }
}
And for now i have this in my controller
public ActionResult Index()
{
var userId = User.Identity.GetUserId();
var messages = db.MessageReceived.Where(p => p.ToUserId == userId).GroupBy(p => p.FromUser.UserName);
return View(messages);
}
This will return the list of Usernames that the user has received a message from, including all the rows that are created when receiving a message. Which is not what I am aiming for. It could end bad when querying for multiple long conversations
Is there a more efficient way to query the list of conversations, than using group by?
If all you need are the list of names that a user has received messages from, a more efficient way to query this is:
var names = db.MessageRecieved.Where(p => p.ToUserId == userId).Select(p => p.FromUser.UserName).Distinct().ToList();

ASP.NET MVC model from db

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;

asp.net MVC CheckboxList from viewmodel

Trying to figure out checkboxlists to implement in a few areas of our system. We have a table, tblJobs. This has a "AllocatedTo" property, which links to the UserID of "tblGlobalUsers". What we want is to be able to select multiple users, iterate through and insert a database record for each user selected to allocate the job to them.
I've tried following some other questions people asked on here, such as Asp.Net MVC4 Display CheckboxList and some other guides, but just getting nowhere with it unfortunately.
Will provide the code that anyone wants, or more information if needed.
Many thanks
Edit:
Have followed the link Stephen provided and attempted to update my viewmodel and controller as required. My viewmodel is now:
public class JobCreateViewModel
{
public string JobTitle { get; set; }
public string Description { get; set; }
public int InventoryID { get; set; }
public int ReportedBy { get; set; }
public int Priority { get; set; }
public int JobType { get; set; }
public int UserID { get; set; }
public string NetworkLogin { get; set; }
public bool IsSelected { get; set; }
public virtual tblGlobalUser GlobalUserAllocated { get; set; }
public virtual tblGlobalUser GlobalUserReportedBy { get; set; }
public virtual tblInventory InventoryHardware { get; set; }
public virtual tblJobType TypeJob { get; set; }
public virtual tblJobPriority JobsPriority { get; set; }
}
public class JobsAllocateViewModel
{
public JobsAllocateViewModel()
{
AllocatedTo = new List<JobCreateViewModel>();
}
public int UserID { get; set; }
public string NetworkLogin { get; set; }
public List<JobCreateViewModel> AllocatedTo { get; set; }
}
And the controller is:
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(JobCreateViewModel viewModel)
{
JobsAllocateViewModel model = new JobsAllocateViewModel();
if(ModelState.IsValid)
{
JobsContext.tblJobs.Add(new tblJob
{
JobTitle = viewModel.JobTitle,
JobDescription = viewModel.Description,
InventoryID = viewModel.InventoryHardware.InventoryID,
ReportedBy = viewModel.GlobalUserReportedBy.UserID,
AllocatedTo = model.AllocatedTo,
Priority = viewModel.JobsPriority.PriorityID,
JobType = viewModel.TypeJob.TypeID
});
JobsContext.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
Getting an error of "Cannot convert type systems.collections.generic.list to int" on AllocatedTo = model.AllocatedTo,

Categories

Resources