I have a users table:
Users: +ID +Username +...
I want to use
myDBContext.Users.Find(Username) to fin a users.
in my current context I can not use his ID.
do i have to use a full LINQ query ? e.g.
var user = from users in myDBContext.Users.Find(Username) where users.Username == username select users
I have also tried to define the username as a primary key in my edmx but that resulted in the following error:
Properties referred by the Principal Role User must be exactly identical to the key of the EntityType CamelotShiftManagementModel.User referred to by the Principal Role in the relationship constraint for Relationship CamelotShiftManagementModel.AssociationUserFK1. Make sure all the key properties are specified in the Principal Role. C:\Code\CamelotShiftManagement\CamelotShiftManagement\Models\CamelotDB.edmx 278 11 CamelotShiftManagement
User myUser = myDBContext.Users.SingleOrDefault(user => user.Username == username);
SingleOrDefault insted of
Single. If user doesn't exist then
Single will throw an error. While
SingleOrDefault will return
null if user not found otherwise
User object will be return.
You can get the user object by using
FirstOrDefault but while selecting which method to use consider below points.
SingleOrDefaultas it will thrown an exception if there are more than one element available.
FirstOrDefaultfor better performance compare to
Firstused when we required single value (first) from the collection or database.
Some other remarks
usernameis primary key then I think there will be no much/no difference between
FirstOrDefaultperformance as primary key has index and search on index column will always be faster than normal column.
SingleOrDefaultwill generate a regular TSQL like "SELECT ...".
FirstOrDefaultmethod will generate the TSQL statment like "SELECT TOP 1..."
I've found it:
User myUser = myDBContext.Users.Single(user => user.Username == i_Username);