0
Dear friends! I have a problem trying to access dbContext with Mysql, for example accessing Context.set(). Add(obj), I get the error message "Object reference not set for an object instance." the project is a simple web api, where the controller accesses the database through a service class that inherits from an abstract class methods for data management (repository class) in the database, inferfaces with standard actions (crud). but still get error.
public class HomeController : Controller
{
private ContatoService _ContatoService;
public ActionResult Index()
{
return View();
}
[HttpPost]
public void Post(Contato obj)
{
_ContatoService = new ContatoService();
_ContatoService.Post(obj);
}
}
public class ContatoService : ContatoRepository, IBaseService<Contato>
{
public void Delete(int id)
{
if (id == 0) throw new ArgumentException("Para realizar a exclusão é necessário identificar o registro.");
Remove(id);
}
public Contato Get(int id)
{
if (id == 0) throw new ArgumentException("Para realizar a seleção da informação é necessário identificar o registro.");
return Select(id);
}
public List<Contato> Get()
{
return SelectAll();
}
public Contato Post(Contato obj)
{
return Insert(obj);
}
public Contato Put(Contato obj)
{
return Update(obj);
}
}
public interface IBaseService<T>
{
T Post(T obj);
T Put(T obj);
void Delete(int id);
T Get(int id);
List<T> Get();
}
public class ContatoRepository: BaseRepository<Contato>
{
}
public abstract class BaseRepository<T> : IDisposable, IRepository<T> where T : class
{
MySQLContext _Context = new MySQLContext();
public void Dispose()
{
_Context.Dispose();
}
public T Insert(T obj)
{
//-- O erro acontece ao acessar _Context...
_Context.Set<T>().Add(obj);
return obj;
}
public void Remove(int id)
{
if (id == 0) throw new ArgumentException("Para realizar essa ação, é necessário informar um identificador.");
_Context.Set<T>().Remove(Select(id));
}
public T Select(int id)
{
if (id == 0) throw new ArgumentException("Para realizar essa ação, é necessário informar um identificador.");
return _Context.Set<T>().Find(id);
}
public List<T> SelectAll()
{
return _Context.Set<T>().ToList();
}
public T Update(T obj)
{
_Context.Entry(obj).State = EntityState.Modified;
return obj;
}
}
public interface IRepository<T> where T : class
{
T Insert(T obj);
T Update(T obj);
void Remove(int id);
T Select(int id);
List<T> SelectAll();
}
public class MySQLContext: DbContext
{
public MySQLContext(): base("MySQLConString") {}
protected override void OnModelCreating(DbModelBuilder modelbuilder)
{
modelbuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelbuilder.Entity<Contato>().ToTable("site_contato");
}
public DbSet<Contato> Contato { get; set; }
}
and "Mysqlconstring" is set in the configuration file? the string is correct?
– Ricardo Pontual
Good morning my friend @Ricardopunctual, yes it is set in my web.config, and it is correct because I use it in a project . net Core.
– Luciano Castilho