Error adding Controler to ASP.NET MVC

Asked

Viewed 50 times

3

A doubt when creating a controller. Because when trying to create it has shown the error of the attached image.

I created 3 small classes: Dependentes, Tipobenef, TitularPlano and ProvaContext

[Table("dependentes")]
public class Dependentes
{
    public int Id { get; set; }
    [Required]
    [MaxLength(100)]
    public string Nome { get; set; }
    //public Tipobenef Tipo { get; set; }
    [Required]
    [ForeignKey("TitularesPlano")]
    public int IdTitularPlano { get; set; }
    public virtual TitularPlano Titular { get; set; }
    public virtual List<Tipobenef> Tipobenefs { get; set; }

}

public enum Tipobenef
{    
    Filho,
    Conjugue,
    Pai,
    Mae        
}

[Table("Titularesplano")]
public class TitularPlano
{
    public int Id { get; set; }
    [Required]
    [MaxLength(100)]
    public string Nome { get; set; }
    public DateTime DataNascimento { get; set; }
    [Required]
    [MaxLength(11)]
    public string CPF { get; set; }
    [Required]
    [MaxLength(8)]
    public string RG { get; set; }
}

public class ProvaContext:DbContext
{
    public ProvaContext():base("Prova")
    {

    }
    public DbSet<TitularPlano> Titulares { get; set; }
    public DbSet<Dependentes> Dependentes { get; set; }

}

Here comes the part about WebConfig:

<add name="Prova"
     providerName="System.Data.SqlClient"
     connectionString="Data Source=Localhost\DESKTOP-T8VEK67; Initial Catalog=DbProva; Integrated Security=True;"/>    

Where I’ve tried every possible name of localhost

Image 1:

inserir a descrição da imagem aqui

Image 2:

inserir a descrição da imagem aqui

1 answer

2


Hi, Bruno, there’s an error in your foreign key statement.

You declare your column and place the FK to the entity by designating the annotation for the attribute that makes the link. In case you designated an annotation that does not exist in the wrong attribute.

...    
public int IdTitularPlano { get; set; }

[ForeignKey("IdTitularPlano")]
public virtual TitularPlano Titular { get; set; }
...

I hope it helps.

  • Thank you very much friend, it worked.

  • 1

    Don’t forget to mark the answer as a solution. Anything the community is available. Hug.

Browser other questions tagged

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