C# - EF Core doubts to create relational model

Asked

Viewed 56 times

1

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

I own a model Curso and a model Unidade, a course has several units and that unit may belong to more than one course.

I made the individual model of Course and Unit, however, my problem is being at the time of creating the relationship model, I was thinking of some way that he received a list of courses and a unit, but without success.

Below I have code examples of my project, while running I’m encountering 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();
}
  • This is a 1-to-many ratio, i.e., 1 unit can have multiple courses. So you can have in the unit class a list of courses: List<Curso> Cursos . Then you can add the courses in the Unit through the List<t> method. Add()

1 answer

1

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

Here says that

to insert explicit values in an IDENTITY column of SQL Server, it is necessary to enable IDENTITY_INSERT manually before calling Savechanges();

Browser other questions tagged

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