I am trying to make a login page. When I try to receive the userdata with linq I get an exception because I try to use Parse in my query. I searched a bit online and found out it is because Linq doesn't recognize Parse. From what I understand I have to translate the not recognisable code to code that linq/slq recognises. Since I have just started using linq queries I have no idea how to accomplish this.
My query:
public static UserDetails GetUser(UserDetails userde)
{
var usr = from u in db.Users
join r in db.Roles on u.RoleId equals r.IdRole
where u.Email == userde.Email && u.Active == true
select new UserDetails
{ Firstname = u.Firstname,
Surname = u.Surname,
Email = u.Email,
Function = u.Function,
Password = u.Password,
Salt = u.Salt,
Userroles = (UserRoles)Enum.Parse(typeof(UserRoles), r.Role1)
};
return usr.FirstOrDefault();
}
I checked these articles:
linq to entities does not recognize method
linq to entities does not recognize the methods system object parsesystem type
you should first use FirstOrDefault() and parse it later. Otherwise linq is still trying to build the select-statement. After FirstOrDefault (or ToList,...) you have your result and can then parse it without problems.
Should be something like this:
public static UserDetails GetUser(UserDetails userde)
{
var usr = from u in db.Users
join r in db.Roles on u.RoleId equals r.IdRole
where u.Email == userde.Email && u.Active == true
select new UserDetails { Firstname = u.Firstname,
Surname = u.Surname,
Email = u.Email,
Function = u.Function,
Password = u.Password,
Salt = u.Salt,
// store the database-value in another property
UserrolesUnparsed = r.Role1
};
// get the database-results
UserDetails details = usr.FirstOrDefault();
// parse the database-value and set it to the property you want to
details.Userroles = (UserRoles)Enum.Parse(typeof(UserRoles), details.UserrolesUnparsed);
return details;
}
sure, there are better/cleaner methods, but this is just to explain you.
Related
I need to write this SQL statement in Entity Framework:
SELECT
SALARIE.MATRICULE, LIEU, UO, UO_RATTACHEMENT,
PHOTO.PHOTO, SALARIE.NOM, SALARIE.PRENOM
FROM
SALARIE, UNITE_ORG, PHOTO
WHERE
SALARIE.LIEU = UNITE_ORG.UO
I use this method for reading my data :
public JsonResult Read()
{
var nodes = entities.UNITE_ORG.Select(p => new NodeModel { id = p.UO, pid = p.UO_RATTACHEMENT, poste = p.POSTE, img=p.LIB_COMPLET, Fullname=p.RESPONSABLE });
return Json(new { nodes = nodes }, JsonRequestBehavior.AllowGet);
}
I need to change this declaration of nodes.
Thank you
I believe that the equivalent Entity Framework would be the following:
var result = (from s in context.SALARIE
from u in context.UNITE_ORG
from p in context.PHOTO
where s.LIEU == u.UO
select new {
MATRICULE = s.MATRICULE,
LIEU = s.LIEU,
UO = u.UO,
UO_RATTACHEMENT = UO_RATTACHEMENT, // I don't know where this is coming from
PHOTO = p.PHOTO,
NOM = s.NOM,
PRENOM = s.PRENOM
}
);
However, this is just a guess from the information you have giving.
Also, like I have stated in my comment, I really think you should stop using the syntax for cross joins that you are doing (the , seperated syntax)
I'm not sure whether it is an emulator issue or not but i have a really simple query
var collectionUri = UriFactory.CreateDocumentCollectionUri(Constants.CosmosDbName, CollectionName);
var spec = new SqlQuerySpec()
{
QueryText = "SELECT * FROM Users u WHERE u.firstName = #firstname",
Parameters = new SqlParameterCollection
{
new SqlParameter{
Name = "#firstname",
Value = value
}
}
};
var query = client.CreateDocumentQuery<User>(collectionUri, spec);
var users = await query.ToListAsync();
the parametrized query returns no results i.e. 0 users
while the same plain query below retuns 1 user that matches the WHERE condition:
spec.Parameters.Clear();
spec.QueryText = $"SELECT * FROM Users u WHERE u.firstName = '{value}'";
query = client.CreateDocumentQuery<User>(collectionUri, spec);
users = await query.ToListAsync(); // returns 1 user
do I need somehow explicitly enable parameterized queries
or am I doing something wrong above with a parameterized query?
According to the Syntax, your query should be like this,
SqlQuerySpec sqlQuerySpec = new SqlQuerySpec
{
QueryText = #"SELECT *
FROM Users u
WHERE u.u.firstName = #firstname",
Parameters = new SqlParameterCollection
{
new SqlParameter("#firstname", value)
}
};
The issue is a kind of var pitfall
the SqlParameter value was taken from an Azure function HttpRequest request:
var value = req.Query["firstname"];
which is
Microsoft.Extensions.Primitives.StringValues value = req.Query["firstname"];
When SqlParameter is created with value of StringValues type it makes slightly different query:
SELECT * FROM Users u WHERE u.firstName = ['Dima']
the brackets ['Dima'] here are excess
the correct query must be without brackets
SELECT * FROM Users u WHERE u.firstName = 'Dima'
so to fix the parameterized query the parameter value should be a string
new SqlParameter("#firstname",value.ToString())
I am using a database-first approach with a custom html helper to get a state of a checkbox using ajax (without using form in the view). I have two tables:
Tbl_1 -> Id, state (true or false), name (name of checkbox)
Tbl_2 -> Id, user_guid, timestamp, Tbl_1Id (foreign_key)
When I do insert operations, it does without any problem but when I try to update it (based upon the logged in user as it also gets GUID, the table gets appended/inserted with new data).
My controller:
public ActionResult SetState(checkboxstate cbstate)
{
var UserId = new Guid(System.Security.Claims.ClaimsPrincipal.Current.FindFirst("sub").Value);
var ent = new StartopDatabaseEntities();
var cbs = ent.checkboxstates.Where(w => w.Name == "World").FirstOrDefault();
if (cbs == null) // when there are no records in the database
{
ent.checkboxstates.Add(cbstate);
ent.checkboxstateUpdates.SingleOrDefault(c => c.Id == cbstate.Id);
var cbsOp = new checkboxstateUpdates();
cbsOp.timestamp = DateTime.Now;
cbsOp.user_guid = UserId;
cbstate.checkboxstateUpdates.Add(cbsOp);
ent.SaveChanges();
} // record in database, update (I've only one user now, so has to update only this one)
else
{
var cbsOp = new checkboxstateUpdates(); // declare in global
var chc = new checkboxstate(); // to be declared in global
var newCbs = ent.checkboxstateUpdates.Include(c => c.checkboxstate).ToList();
foreach (var u in newCbs)
{
if(u.user_guid==UserId && u.CheckboxStateId == u.checkboxstate.Id)
{
chc.state = cbstate.state;
chc.name = cbstate.name;
ent.checkboxstates.Add(chc);
cbsOp.Tidspunkt = DateTime.Now;
cbsOp.OpdateretAfBruger = UserId;
ent.checkboxstateUpdates.Add(cbsOp);
ent.SaveChanges();
}
}
}
Can anyone explain please why it's not updating but appending/inserting same data with a new Id (primary key)? I have a simple view where Ajax sends a call to the controller with the state and name of the checkbox. I have also tried
Db.Entry(obj).state = EntityState.Modified
without any help
You have not written the code for the logic which want to achieve..
I am not clear on the logic of if block also but the else part can be fixed as following.
var newCbs = ent.checkboxstateUpdates.Include(c => c.checkboxstate).Where(u.user_guid == UserId).FirstOrDefault();
if(newCbs != null) {
newCbs.checkboxstate.state = cbstate.state;
newCbs.checkboxstate.name = cbstate.name;
newCbs.Tidspunkt = DateTime.Now;
newCbs.OpdateretAfBruger = UserId;
ent.SaveChanges();
}
Solved this with the help from #David & #Chetan:
I did some modify in the code as per David:
u.checkboxstate.state=cbstate.state;
u.checkboxstate.name=cbstate.name;
u.timestamp=DateTime.Now;
ent.saveChanges();
I was using the wrong logic i.e. getting instance of the class rather than the 'ent' object. Thanks guys for the help.
I wrote a common query in my web application using linq but after executing i got this error :
Explicit construction of entity type 'AccidentCongress.dblinqtoDb.tblpayment' in query is not allowed.
My query is :
public List<tblpayment> returnpay(string uname)
{
List<tblpayment> q = (from i in db.tblpayments
where i.ownerUsername == uname
select new tblpayment
{
id = i.id
}).ToList();
return q;
}
I searched this problem but i couldn't find any useful solution.
Thank you .
There's a good explanation of the exception here:
https://stackoverflow.com/a/2953058/59849
Are you sure you need to construct a new instance of tblpayment in your query? Can you just do something like this:
public List<tblpayment> returnpay(string uname)
{
List<tblpayment> q = (from i in db.tblpayments
where i.ownerUsername == uname
select i).ToList();
return q;
}
If you really do need to create a new list of tblpayment objects based on your query, you could do it like this:
public List<tblpayment> returnpay(string uname)
{
List<tblpayment> q = (from i in db.tblpayments
where i.ownerUsername == uname
select i).ToList();
return q.Select(x => new tblpayment { id = i.id }).ToList();
}
I have implemented a LINQ to SQL based RoleProvider, when I assign role to a user following exception is thrown while AddUsersToRoles method is called. I have defined a composite primary key userid & roleId on this table, it still throwing this exception:
Can't perform Create, Update or Delete
operations on 'Table(UsersInRole)'
because it has no primary key.
My LinQ to SQL implementation of AddUsersToRoles method is as follows. It breaks at db.UsersInRoles.InsertOnSubmit(userInRole);
using (RussarmsDataContext db = new RussarmsDataContext())
{
List<UsersInRole> usersInRole = new List<UsersInRole>();
foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
UsersInRole userInRole = new UsersInRole();
object userId = ProvidersUtility.GetUserIdByUserName(username,applicationName);
object roleId = ProvidersUtility.GetRoleIdByRoleName(rolename,applicationName);
if (userId != null && roleId != null)
{
userInRole.UserId = (Guid)userId;
userInRole.RoleId = (Guid)roleId;
db.UsersInRoles.InsertOnSubmit(userInRole);
}
}
}
try
{
// db.UsersInRoles.InsertAllOnSubmit(usersInRole);
db.SubmitChanges();
}
catch (ChangeConflictException)
{
db.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);
db.SubmitChanges();
}
}
Any help will be appreciated.
Thanks.
LINQ to SQL does not natively support many to many... the joining table has to have two foreign key columns PLUS 1 primary key column with the IDENTITY attribute.