I'm trying to make works a login functionality but for some users Linq return some values as null when they have a correct value in database. For other users everything works ok.
This is my linq
public Clientes Login(string username)
{
DataClasses1DataContext db = new DataClasses1DataContext();
var query = from c in db.Clientes
where c.NroDocumento == username
select c;
return query.FirstOrDefault();
}
Then in the service layer I have the following:
Clientes o = userData.Login(username);
return (o != null && password == o.Password)
? new UserEntity(o.CodCliente, o.Email, o.Empresa)
: null;
But when I debug, for some users I can see that the property o.Password has a value, and for others it appears as null.
The users are being created by other systems, so I don't know if that can impact, but when I run the Select directly in SQL Server, both users has a Password, so I don't understand which is the difference that makes Linq return null.
This is the image of the model (sorry for the spanish)
As per the comments it looks like there are duplicates, but some of them don't have a password. As you're using 'FirstOrDefault' in some cases it's picking up the one without a password.
Related
I have written a stored procedure for getting details from database table. While executing that stored procedure, I get the correct results, but on my page, I only get 5 out of 6 column values from the stored procedure output. I only get values up to dataReader[4]:
public List<User> ShowDetailsFromDB()
{
using (adoHelper = new AdoHelper(connectionString))
{
List<User> users = new List<User>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
User user = new User();
user.userId = dataReader[0] as string;
user.password = dataReader[1] as string;
user.userName = dataReader[2] as string;
user.email = dataReader[3] as string;
user.phone = dataReader[4] as string;
user.userRegId = dataReader[5] as string;
users.Add(user);
}
return users;
}
}
USE [TryLocal]
GO
ALTER procedure [dbo].[GetDetails]
as
begin
select
registration.UserId,
registration.Password,
registration.UserName,
registration.Email,
registration.Phone,
registration.RegID
from Registration registration
Right JOIN dbo.UserAddress useraddress ON
registration.RegID=useraddress.UserRegId
group by
registration.UserId,registration.Password,registration.UserName,
registration.Email,
registration.Phone,
registration.RegID
order by(registration.UserName)
end
The problem is this line:
user.userRegId = dataReader[5] as string;
datareader[5] is not a string! It's an integer, and in C# you can't just cast from int to string; it wants to be aware of the different culture and formatting options, where a cast to string is ambiguous. Therefore the as operator here will always produce null.
Instead you can call dataReader[5].ToString(), or dataReader.GetInt32(5), or (int)dataReader[5]. I would expect any of those to work. And if there's any chance this field could be NULL in the database you also want to check for DBNull.Value somewhere.
While I'm here... plain text passwords in the database are NOT OKAY, not even for testing or learning. If you're doing this just as a learning system for practice, build something that doesn't need authentication.
I am using Linq in a simple IronPython script to perform a lookup against an entity framework database context:
import clr
import System
clr.AddReference('Common')
clr.AddReference('System.Core')
clr.ImportExtensions(System.Linq)
from Common import Message
db = Lib.Data.db #Lib passed into environment
#RequestMessage passed into environment
username = RequestMessage.Data.Username
password = RequestMessage.Data.Password
#outputs the username as expected
System.Console.WriteLine(username)
#always returns null
users = db.Users.FirstOrDefault(lambda x: x.Username == username)
#returns expected data
users = db.Users.FirstOrDefault(lambda x: x.Username == 'someuser')
The above code works just fine if I substitute username for a hardcoded string containing an actual username in the database. When i use the variable itself, the expression always evaluates to null/None.
I have this weird problem that has burned way more hours than it should.
My main question is this:
What may cause EF 4.1 Code First to set a foreign key to NULL when an entity is added?
The problem is this: I have a list of users on file, and these users must be inserted to my database if they're not already there.
I have something like this:
foreach (var u in usersFromFile) {
var userProfile = context.Users
.FirstOrDefault(user=>
user.EmployeeId == u.EmployeeId && user.CompanyId == 1);
if (userProfile == null) {
User newUser = new User();
newUser.EmployeeId = u.EmployeeId;
newUser.CompanyId = 1;
context.Users.Add(newUser); //This will sometimes set CompanyId = NULL
}
}
context.SaveChanges();
Some users won't be added to the Users table correctly.
They get CompanyId == NULL, and as such they do not belong to the company.
I also tried injecting SQL directly like so:
var query = #"INSERT INTO [dbo].[Users]
([CompanyId],[EmployeeId]) VALUES (3,#emplid)";
context.Database.ExecuteSqlCommand(query, new SqlParameter[] {
new SqlParameter("emplid", u.EmployeeId)});
I have tried to access the Users list on the Company object. That does not work.
I have tried to use context.Users.Create() instead of new User(). Does not change anything.
I have tried to inject SQL, still the same problem. That exact SQL works, if ran from the Studio Manager.
I have tried to context.SaveChanges() after each add, nothing changed.
I know for a fact that the state of the entity about to be added is correct, also in the cases where CompanyId is set to NULL.
Could there be something with my underlying database?
Thank you so much for your time and help!
Try the following:
foreach (var u in usersFromFile) {
if (context.Users.Any(
user=>
user.EmployeeId == u.EmployeeId && user.CompanyId == 1)
)
{
User newUser = new User();
newUser.EmployeeId = u.EmployeeId;
newUser.CompanyId = 1;
context.Users.Add(newUser); //This will sometimes set CompanyId = NULL
}
}
context.SaveChanges();
The Any() function checks wether a user based on the given query exists.
Also, don't forget to add the context.savechanges to make sure every added record gets put in the database.
Lastly, you checked if user.CompanyId = 1, should be == 1
I ended up transforming the list of users to a series of SQL statemens, and running them through context.Database.ExecuteSqlCommand(sql).
It's dirty but it works.
If anyone has any good ideas as to why the FK CompanyId on the user entity is sometimes set to NULL I'd we very happy if you share your ideas.
I have a table users which stores three values i.e username ,the password and the member type .I want to ensure that the username stored in the table is unique and hence there is a primary key on it.However I want to do the validation at the client side itself instead of sending a insert request to the database and then catching the error .
So how can I retrieve the single record from the database which would contain both username and password so that I can use it for the comparison purposes in the code and then throw a validation error if needed.
My manager wants me to use stored procedures so inputs along those lines would be great
public static bool IsUserExists(string userName, string hashedPassword)
{
bool result = false;
using (MyEntities entityContext = new MyEntities())
{
result = (entityContext.User.Count(u => u.username == userName &&
u.password == hashedPassword) == 1);
}
return result;
}
Currently, I'm developing an application that depends on (and thus connects to) various databases via LINQ-to-SQL. For one of the databases, the connection string may vary and is thus configurable - however, the schema of this database is identical for all connection strings.
Because of the configurable connection string, I want to validate the DataContext during the startup of my application, to make sure that all tables and views my application uses, are available.
The Table<T> objects in the DataContext object are always initialized - even if the corresponding SQL table or view doesn't have any records.
So then. Currently, the validation check is performed as follows:
bool valid = _dataContext.Articles.Count() > 0
&& _dataContext.Customers.Count() > 0
&& _dataContext.Orders.Count() > 0;
While this does work, the determination of the value of valid takes quite some time (every record of each Table is touched), which ultimately results in a time out. So, is there a faster, more reliable way to determine whether or not a Table<T> of a certain DataContext really exists as a table in the corresponding database?
Here is an (untested) idea:
Grab the name of your table. You can hard code it in, or you can grab it programmatically via
TableAttribute attribute = (TableAttribute)typeof(MyTableObject)
.GetCustomAttributes(typeof(TableAttribute), true)
.Single();
string name = attribute.Name;
MyTableObject is the LINQ-to-SQL generated object contained in your Table, i.e., the generic parameter T in Table<T>.
(TableAttribute is in System.Data.Linq.Mapping.)
Use the DataContext.ExecuteQuery method as in
var db = new MyDataContext();
var results = db.ExecuteQuery<string>("SELECT name FROM dbo.sysobjects WHERE xtype = 'U'");
bool hasTable = results.Any(s => "dbo." + s == name);
A slight change on Jason's answer (I gave him an upvote :))
public bool TableExistsInDatabase<T>()
{
TableAttribute attribute = (TableAttribute)typeof(T)
.GetCustomAttributes(typeof(TableAttribute), true)
.Single();
var result = ExecuteQuery<bool>(
String.Format(
"IF OBJECT_ID('{0}', 'U') IS NOT NULL
SELECT CAST(1 AS BIT) ELSE
SELECT CAST(0 AS BIT)", attribute.Name));
return result.First();
}