How to map a table without PK with entityframework?

Asked

Viewed 289 times

0

Guys! in my project ,I am having difficulties in mapping a table without Primary key(PK),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");
    }
}

1 answer

1

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

Do it this way:

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, it is not possible to create Models without PK. The amount of bugs simply does not pay to insist on the approach.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.