-6

I need to get only one value from the table, I do it like this:

public DBEntities db = new DBEntities();
public ObservableCollection<Users> GetUsers
{
   get { return db.Users.Local; }
}
public WindowViewModel(Label userName)
{
    var us = GetUsers.Where(u => u.Id == 1) as Users;
    userName = us.Name.ToString();
}

But it does not work out the error: Additional information: The object reference does not point to an instance of the object.

Nooruz
  • 19
  • 7
  • https://stackoverflow.com/a/218510/5246145 – 3615 Dec 01 '17 at 12:15
  • Sounds like a null reference exception, mayby this article will help; https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Undeadparade Dec 01 '17 at 12:16
  • 1
    You need some basic LINQ knowledge. – Ivan Stoev Dec 01 '17 at 12:16
  • Some usefull links [LINQ: .NET Language-Integrated Query](https://msdn.microsoft.com/en-us/library/bb308959.aspx) ---- [LINQ to Entities](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/linq-to-entities) – Celso Lívero Dec 01 '17 at 12:29
  • `as Users;` should be `.FirstOrDefault();` – mjwills Dec 01 '17 at 12:35

1 Answers1

0

Let me give you some direction

Do not use a propertie to get your data, use a method

like this:

//returns an enumeration of users filtered by the given expression
Public IEnumerable<User> GetUsers(Expression<Func<User, bool>> expression)
{
    return db.Users.Where(expression);
}
// returns the first occurency of a user filtered by the given expression
Public User GetUser(Expression<Func<User, bool>> expression)
{
    return db.Users.FirstOrDefault(expression);
}

usage:

var user = GetUser(u => u.Id == 1);     // returns first occurency or null
var users = GetUsers(u => u.Id < 100); 

and you have a label, it is an object, with properties where you should set the information, so set your Name to its Content:

public WindowViewModel(Label userName)
{
    var us = GetUser(u => u.Id == 1);
    userName.Content = us.Name.ToString();
}
Celso Lívero
  • 621
  • 2
  • 14
  • 16
  • Thanks for your reply. At me still a problem the second method again returns the same error: Additional information: The reference to the object does not point to an instance of the object. – Nooruz Dec 01 '17 at 13:31
  • this can help you -> http://www.entityframeworktutorial.net/entityframework6/introduction.aspx – Celso Lívero Dec 01 '17 at 14:58