1
command = "INSERT INTO clients VALUES(" + NameTB.Text +")";
objCtx.SaveChanges();

List<Client> clients = new List<Client>();
clients = objCtx.ExecuteStoreQuery<Client>("Select * from clients").ToList();

string x = "";
for (int i = 0; i < clients.Count; i++)
     x += clients[i].Name.ToString();//exception here

MessageBox.Show(x);

I just start to work with EF and have no idea how to fix this; I took the code from here

1
  • 2
    Warning !!! SQL Injection Commented Apr 24, 2014 at 11:22

1 Answer 1

2

Sounds like the Name property is null in the Client data that is returned.

Either have a constraint in the database that this field is required or add a null check:

string x = "";
for (int i = 0; i < clients.Count; i++) {
     if (!String.IsNullOrEmpty(clients[i].Name)) {
          x += clients[i].Name.ToString();
     }
}

Also, if you're going to work with many clients and your string is going to get big I suggest you take a look at StringBuilder.

Sign up to request clarification or add additional context in comments.

7 Comments

how do I add a constraint in the database?
@MihaiBratulescu Which database are you working with?
mdf, is that what you are asking for?
@MihaiBratulescu Isn't that SQL or something ? take a look here stackoverflow.com/questions/689746/…
I just noticed I forgot to execute the SQL command so there is no data in the table so my question now is why is the length on the list 3 and not 0?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.