I'm learning about Entity Framework and I am currently facing a problem where I take about 10 seconds to retrieve data from a database or to update a row, as if my code were actually stuck for a period of time, even though debugging it everything went normal.
The code itself, actually works as expected, besides this delay.
Searching on Google and here I did not found other people with this issue related to Entity Framework.
I think that maybe it's something to do with my CodeFirstMySQLEntities
class constructor, but not sure.
If someone could provide me with a guidance, I would appreciate.
This is the main code:
namespace CodeFirstMySQL
{
class Program
{
static void Main(string[] args)
{
UserRepository userRepository = new UserRepository();
userRepository.Update("Klein", "OtherName");
//delay experienced here
Console.WriteLine("done");
Console.ReadLine();
}
}
}
This is the DbContext code:
namespace CodeFirstMySQL.Database
{
public class CodeFirstMySQLEntities : DbContext
{
public CodeFirstMySQLEntities() : base("CodeFirstMySQLEntities") { }
public DbSet<UserModel> Users { get; set; }
}
}
This is the UserModel code:
namespace CodeFirstMySQL.Database.Models
{
public class UserModel
{
[Key, StringLength(100)]
public string firstName { get; set; }
[StringLength(100)]
public string lastName { get; set; }
}
}
This is the repository code:
namespace CodeFirstMySQL.Database.Repositories
{
public class UserRepository
{
public void Insert(UserModel user)
{
using (var context = new CodeFirstMySQLEntities())
{
context.Users.Add(user);
context.SaveChanges();
}
}
public void Delete(string firstName)
{
using (var context = new CodeFirstMySQLEntities())
{
UserModel user = context.Users.FirstOrDefault(x => x.firstName == firstName);
context.Users.Remove(user);
context.SaveChanges();
}
}
public void Update(string lastNameOld, string lastNameNew)
{
using (var context = new CodeFirstMySQLEntities())
{
UserModel user = context.Users.FirstOrDefault(x => x.lastName == lastNameOld);
user.lastName = lastNameNew;
context.SaveChanges();
}
}
public IList<UserModel> GetUsers()
{
using (var context = new CodeFirstMySQLEntities())
{
return context.Set<UserModel>().ToList();
}
}
}
}
Connection String:
<connectionStrings>
<add name="CodeFirstMySQLEntities" connectionString="Server=localhost; Database=CodeFirst; Uid=root; Pwd=" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…