How to map a table without PK with entityframework?

0

Everyone! in my project, I'm having trouble mapping a primary keyless (PK) table, the application is breaking, when I implement the table in the MAP of my project.

    public class Configuracoes
{
    public int MaximoFilas { get;  set; }
    public int QtdSenhasEspera { get;  set; }
    public string NomeEmpresa { get; set; }
    public string EnderecoEmpresa { get; set; }

}



 public class ConfiguracoesMap : EntityTypeConfiguration<Configuracoes>
{
    public ConfiguracoesMap()
    {

        this.ToTable("Configuracoes");
    }
}
    
asked by anonymous 12.03.2015 / 18:36

1 answer

1

This is not how you map a table that will have only one record.

Do as follows:

public class Configuracoes
{
    [Key]
    public Guid ConfiguracoesId { get; set; }
    public int MaximoFilas { get;  set; }
    public int QtdSenhasEspera { get;  set; }
    public string NomeEmpresa { get; set; }
    public string EnderecoEmpresa { get; set; }
}

Controller:

public class ConfiguracoesController : Controller 
{
    private MeuContexto context = new MeuContexto();

    public ActionResult Index()
    {
        var configuracoes = context.Configuracoes.FirstOrDefault();
        return View(configuracoes ?? new Configuracoes { ConfiguracoesId = Guid.NewGuid() });
    }

    [HttpPost]
    public ActionResult Index(Configuracoes configuracoes) 
    {
        if (ModelState.IsValid)
        {
            var configuracoesOriginais = context.Configuracoes.AsNoTracking().FirstOrDefault();
            if (configuracoesOriginais != null) {
                context.Entry(configuracoes).State = EntityState.Modified;
            } else {
                context.Configuracoes.Add(configuracoes);
            }
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(configuracoes);
    }
}

But answering the original question, you can not create Models without PK. The amount of bugs simply does not pay to insist on the approach.

    
12.03.2015 / 19:36