My db table structure is
ClaimsTable
Id (int) UserId (FK) ClaimType (string) ClaimValue (string)
1 1 Role Administrator
I'm not tracking claims from users side, so when I need users claim I load manually.
RIght now I have simple linq question but I cannot see way out from here
I'm loading users claims and I want to check does that claim match with one passed as an argument
public bool HasClaim(User user, string type, string value)
{
var claimsRepository = ... claimsrepository init ....
var userClaims = claimsRepository.FindAll().Where(usr => usr.User == user).ToList();
if (userClaims.Count() > 0)
{
// linq statement to select those claims which has type and value
// equal to method parameters
bool containsClaim = ?????
if (containsClaim == true)
return true;
}
return false;
}
I believe you are looking for:
return claimsRepository.FindAll().Any(user => user.User == user &&
user.ClaimType == type &&
user.ClaimValue == value);
Related
I hope this question respects the StackOverflow guidelines.
I have a table (ResultsTable) in my DB (SQL Server management studio) in which the columns are:
ID (PK, FK, int, not null)
RiskRate (PK, int, not null)
FileName (PK, nvarchar(100), not null)
In C# I've used EF. In my code, there is a method SelectFileNames(string fileName):
var resultSearch = (from result in DB.ContextManagement.ResultTable
where result.FinaName.compareTo(fileName) == 0
select result).FirstOrDefault();
if (resultSearch == null)
...
else
...
The FirstOrDefault() method has this description:
Returns the first element of the sequence that satisfies a condition
or a default value (TSource) if no such element is found.
So, how can I force FirstOrDefault() to return null if there isn't an element with that filename? NB: in my table ResultTable, the columns have the not null constraint.
Thanks.
If in your query
(from result in DB.ContextManagement.ResultTable
where result.FinaName.compareTo(fileName) == 0
select result)
no entity respect your condition then the FirstOrDefault will return null.
It is specified in the documentation
"Remarks
The default value for reference and nullable types is null."
Since the type of result is a reference type it will return null.
try like this .
List<Users> userlist = new ();
userlist.Add(new Users() {username = "testuser",password = "testpass"});
userlist.Add(new Users() { username = "testuser2", password = "" });
var result = userlist.FirstOrDefault(s => s.username == "testuser2")?.password;
You can use the following syntaxe
var resultSearch = DB.ContextManagement.ResultTable.Where(x => x.FileName == fileName).ToList() ;
if (resultSearch.Count > 0)
...
else //Get the first element of list
I'm fairly new with updating databases, and I've constructed the below code to replace a user's role with a new role. I'm getting the error in the subject though.
public void UpdateRole(string id, string newRoleID)
{
var user = Users.FirstOrDefault(u => u.Id == id);
var oldRoleId = user.Roles.FirstOrDefault().RoleId;
if (user != null && oldRoleId != newRoleID)
{
user.Roles.Remove(oldRoleId);
user.Roles.Add(newRoleID);
}
}
Could someone please explain why I am getting this error? I am not trying to convert anything. I am attempting to delete the contents of RoleId for the user id specified, and replace it with the new ID that is sent from my post action.
user.Roles.Add method takes a IdentityUserRole object while you are passing it a string value (i.e. newRoleID). You need the following change in you code:
user.Roles.Add(new IdentityUserRole { RoleId = newRoleID });
Edit
The Remove method, needs an IdentityUserRole object too. But note that it must be attached to the context too. The simplest way you can do it is through the following code:
var user = Users.FirstOrDefault(u => u.Id == id);
var oldRole = user.Roles.FirstOrDefault();
if (user != null && oldRole.RoleId != newRoleID)
{
user.Roles.Remove(oldRole);
user.Roles.Add(new IdentityUserRole { RoleId = newRoleID });
}
I have a table named dbo.EmployeeType with three records:
PK_EmployeetypeID EmployeeTypeName
1 Project Manager
2 Business Analyst
3 Developer
I have this piece of Linq code:
public static string GetTypeByID(int id)
{
using (ProjectTrackingEntities1 db = new ProjectTrackingEntities1())
{
var type = db.EmployeeTypes.Select(o => new LOOKUPEmployeeType
{
PK_EmployeeTypeID = id,
EmployeeTypeName = o.EmployeeTypeName
});
return type.FirstOrDefault().EmployeeTypeName;
}
}
No matter what id I send to it, it returns Project Manager, and I'm confused as to why.
You need to apply a filter, otherwise you're just returning the first record and hard coding the ID. Try this:
public static string GetTypeByID(int id)
{
using (ProjectTrackingEntities1 db = new ProjectTrackingEntities1())
{
//Here we apply a filter, the lambda here is what creates the WHERE clause
var type = db.EmployeeTypes
.FirstOrDefault(et => et.PK_EmployeeTypeID == id);
if(type != null)
{
return type.EmployeeTypeName;
}
else
{
return "";
}
}
}
Note that using FirstOrDefault means if there are no matches, or multiple matches, type will be null and you will get an empty string returned.
Set a breakpoint on type = ... and inspect it. You have no Where in there so you get all - and Select just makes LOOKUPEmployeeTypes out of all of them.
FirstOrDefault then returns the first of those 3 which is always the ProjManager
Fix:
var type = db
.EmployeeTypes
.Where( o => o.Id == id)
.Select(o => new LOOKUPEmployeeType
{
PK_EmployeeTypeID = id,
EmployeeTypeName = o.EmployeeTypeName
});
In your code you only return the first value. You need to tell EF which value you need to return.
Let us assume you need the value with Id=2. Instead of Select(), use Single(x => x.Id == 2) or First(x => x.Id == 2).
I Need Help to check Case Sensitivity of LoginId & Password Like Admin and Password : SsA.123 but currently it takes admin as LoginId and ssa.123 as Passwod.
public static class LoginValidation
{
//VALIDATE LOGIN AND GET USER NAME AND USER ID FOR FUTURE USE
public static bool Validate_Login(string first_input, string password, DBEntities db, out string Name, out int id)
{
Name = db.MAST_User.Where(x => x.LoginId == first_input).Select(x => x.UserName).FirstOrDefault();//GET USER NAME TO DISPLAY AFTER LOGIN
id = db.MAST_User.Where(x => x.LoginId == first_input).Select(x => x.MastId).FirstOrDefault(); //GET USER ID TO CHECK RIGHTS
return db.MAST_User.First(x => x.LoginId == first_input).Password == password ? true : false; //RETURNS BOOLEAN VALUE TRUE OR FALSE
}
}
Your comparison query is executing within the database server and it may have set to be case insensitive (for example SQL server is case insensitive by default).
Easiest way would be to bring your query results to memory by converting it to an Array()/List()/Variable and then compare within C# code. Ex;
//Load into memory
var users = db.MAST_User.Where(x => x.LoginId == first_input).ToArray();
//Compare in C#
if(users.Any(u=> u.LoginId == first_input && u.Password == password))
{
return true;
}
return false;
On a separate note, please check your FirstOrDefault() object for null before assigning its properties to other variables.
I have a DB table that looks similar to this.
ID | Status | Type
etc...etc
I am using linq to try and discern distinct Statuses from this collection like so
results = ctx.Status.Distinct(new StatusComparer()).ToList();
but this returns all statuses, I used the following Link to construct the Comparer below, I found that suggestion in another StackOverflow Post
public class StatusComparer : IEqualityComparer<Status>
{
public bool Equals(Status x, Status y)
{
// Check whether the compared objects reference the same data.
if (ReferenceEquals(x, y))
{
return true;
}
// Check whether any of the compared objects is null.
if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
{
return false;
}
// Check whether the status' properties are equal.
return x.StatusDescription == y.StatusDescription && x.Type == y.Type && x.StatusID == y.StatusID;
}
public int GetHashCode(Status status)
{
// Get hash code for the Name field if it is not null.
var hashStatusId = status.StatusID.GetHashCode();
// Get hash code for the Code field.
var hashStatusDescription = status.StatusDescription.GetHashCode();
var hashStatusType = status.Type.GetHashCode();
// Calculate the hash code for the product.
return hashStatusId ^ hashStatusDescription ^ hashStatusType;
}
}
}
My problem is as follows early on we had a system that worked fine, so well in fact they wanted another system using the same Database so we plumbed it in. The search has an advanced options with several filters one of them being Status but as you can see from the above (loose) DB structure statuses have different types but similar text. I need to be able to select via Linq the whole status by the distinct text. all help would be greatly appreciated.
have also tried
results = (from s in context.Status group s by s.StatusDescription into g select g.First()).ToList();
this also failed with a System.NotSupportedException
To select all distinct statuses:
ctx.Status.Select(s => new { s.StatusDescription, s.Type }).Distinct();