1
\$\begingroup\$

I'm creating a system and I'm using EF with Linq. I create my Model (.edmx) and using it, I generated my database and my classes. Like the Usuario (user in Portuguese going to keep the names in Portuguese to avoid some misleading).

namespace SistemaBox.Model
{
 public partial class Usuario
 {
 public int Codigo { get; set; }
 public string Nome { get; set; }
 public string Sobrenome { get; set; }
 public string Senha { get; set; }
 public DateTime DataCriacao { get; set; }
 public DateTime DataUltimoLogin { get; set; }
 public virtual PermissaoGrupo CodigoPermissaoGrupo { get; set; }
 }
}

After this, I create my controller class:

namespace SistemaBox.Controller
{
 [Serializable]
 public class ZUsuario : Usuario
 {
 String connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
 /// <summary>
 /// Cadastro e edição
 /// </summary>
 public void Cadastro()
 {
 if (Codigo != null && Codigo > 0)
 {
 // Cadastro
 using (DataContext db = new DataContext(connString))
 {
 Table<Usuario> Usuarios = db.GetTable<Usuario>();
 var query =
 from usr in Usuarios
 where usr.Nome == "Test"
 select usr;
 foreach (var usr in query)
 Console.WriteLine("id = {0}, City = {1}", usr.Codigo, usr.Nome);
 }
 }
 else
 {
 // Edição
 }
 }
 }
}

Please ignore the fact that the class name is record and I'm doing a select. It is just for tests.

My question is about the controller. Is the right way to declare the connection String as global:

String connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

and use the using like I'm doing?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 19, 2013 at 19:41
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Your connection string is actually a private class member. I would probably put private keyword explicitly to make it clear.

connString is going to be initialized each time the class instance is created. But the connection string is not going to change in run time so it worth to make connStrint a static member.

answered Feb 21, 2013 at 10:25
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.