C # - EF Core questions to create relational model

1

I'm starting in Asp Net Core and I have the following question:

I have a Curso template and a Unidade template, a course has multiple units, and that unit can belong to more than one course.

I did the individual Course and Unit model, but my problem is being in the process of creating the relationship model, I was thinking in some way that it would receive a list of courses and a unit, but without success

Below are code examples of my project, while running I'm encountering the error Identity_Insert .

Modelo de curso
public class Curso
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    [Key]        
    public long curId { get; set; }

    [Required]
    [StringLength(80)]
    public string curDescricao { get; set; }

    [Required]
    [StringLength(1)]
    public string curStatus { get; set; }

    [StringLength(20)]
    public string curCodExterno { get; set; }

    [StringLength(60)]
    public string curObservacao { get; set; }
}

Modelo de unidade
public class Unidade
{        
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    [Key]
    public long uniId { get; set; }
    [Required]
    [StringLength(80)]        
    public string uniDescricao { get; set; }
    [Required]
    [StringLength(1)]
    public string uniStatus { get; set; }
    [StringLength(20)]
    public string uniCodExterno { get; set; }
    public byte[] uniImagem { get; set; }
}

Modelo de CursoUnidade
public class CursoUnidade
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    [Key]
    public long cuuId { get; set; }

    /*[Required]        
    public long cuuCurId { get; set; }
    [ForeignKey("cuuCurId")]*/        
    public List<Curso> Curso { get; set; }

    /*[Required]
    public long cuuUniId { get; set; }
    [ForeignKey("cuuUniId")]        */
    public Unidade Unidade { get; set; }
}

Serviço de unidade
public void AddTeste(CursoUnidade cursoUnidade)
{
    _contexto.Add(cursoUnidade);
    _contexto.SaveChanges();
}
    
asked by anonymous 04.09.2018 / 20:29

1 answer

1

Probably somewhere you should be explicitly setting the value of some primary key column. Since you have set your primary keys as identity, they will be incremented automatically, and you will throw an exception if you try to set the value of any key with this constraint.

Here says

  

To insert explicit values into a SQL Server IDENTITY column, you must enable IDENTITY_INSERT manually before calling SaveChanges ();

    
04.09.2018 / 23:33