POST method in the ASP.NET Controller API is auto-incrementing foreign key even if the value should be empty

Asked

Viewed 27 times

0

I have the following code:

public ActionResult Post(Project project)
  {
    try
      {            
         _acess.AddProject(project);
      }
    catch(DataException ex)
      {
         BadRequest(ex.Message);
      }
      return Ok();
  }

Sent JSON object:

{
  "Id": 0,
  "Name": "string",
  "Image": "string",
  "Why": "string",
  "What": "string",
  "WhatWillWeDo": "string",
  "ProjStatus": 0,
  "Course": {
    "CourseId": 0,
    "Name": "string"
  },
  "CourseId": 0
}

Project class:

public class Project
{
    [Key]
    public int Id { get; set; }
    [Required(ErrorMessage = "Nome é obrigatório")]
    public string Name { get; set; }
    public string Image { get; set; }
    public string Why { get; set; }
    public string What { get; set; }
    public string WhatWillWeDo { get; set; }
    public ProjectStatus ProjStatus { get; set; }
    public Course Course { get; set; }

    public int CourseId { get; set; }

    public enum ProjectStatus
    {
        development = 0,
        publicated = 1
    }
}

Course class

public class Course
{
    [Key]
    public int CourseId { get; set; }

    public string Name { get; set; }
}

Content class

    public class StreamerContext : DbContext
    {
        public StreamerContext(DbContextOptions<StreamerContext> option) : base(option) {}

        public StreamerContext() : base()
        {

        }

        public DbSet<Course> Course { get; set; }
        public DbSet<Project> Project { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=SS_DB.db");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Project>().ToTable("Project");
            modelBuilder.Entity<Project>().HasKey(pre => pre.Id);
            modelBuilder.Entity<Project>().Property(pre => pre.Id).HasColumnName("id");
            modelBuilder.Entity<Project>().Property(pre => pre.Name).HasColumnName("name");
            modelBuilder.Entity<Project>().Property(pre => pre.Image).HasColumnName("image");
            modelBuilder.Entity<Project>().Property(pre => pre.Why).HasColumnName("why");
            modelBuilder.Entity<Project>().Property(pre => pre.What).HasColumnName("what");
            modelBuilder.Entity<Project>().Property(pre => pre.WhatWillWeDo).HasColumnName("whatWillWeDo");
            modelBuilder.Entity<Project>().Property(pre => pre.ProjStatus).HasColumnName("projStatus");
            modelBuilder.Entity<Project>().Property(pre => pre.CourseId).HasColumnName("courseId");

            modelBuilder.Entity<Course>().ToTable("Course");
            modelBuilder.Entity<Course>().HasKey(pre => pre.CourseId);
            modelBuilder.Entity<Course>().Property(pre => pre.CourseId).HasColumnName("id");
            modelBuilder.Entity<Course>().Property(pre => pre.Name).HasColumnName("name");
        }
    }
}

Add Method

public void AddProject(Project item)
  {
    context.Project.Add(item);
    Save();          
 }

Override method of context

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Project>().ToTable("Project");
            modelBuilder.Entity<Project>().HasKey(pre => pre.Id);
            modelBuilder.Entity<Project>().Property(pre => pre.Id).HasColumnName("id");
            modelBuilder.Entity<Project>().Property(pre => pre.Name).HasColumnName("name");
            modelBuilder.Entity<Project>().Property(pre => pre.Image).HasColumnName("image");
            modelBuilder.Entity<Project>().Property(pre => pre.Why).HasColumnName("why");
            modelBuilder.Entity<Project>().Property(pre => pre.What).HasColumnName("what");
            modelBuilder.Entity<Project>().Property(pre => pre.WhatWillWeDo).HasColumnName("whatWillWeDo");
            modelBuilder.Entity<Project>().Property(pre => pre.ProjStatus).HasColumnName("projStatus");
            modelBuilder.Entity<Project>().Property(pre => pre.CourseId).HasColumnName("courseId");

            modelBuilder.Entity<Course>().ToTable("Course");
            modelBuilder.Entity<Course>().HasKey(pre => pre.CourseId);
            modelBuilder.Entity<Course>().Property(pre => pre.CourseId).HasColumnName("id");
            modelBuilder.Entity<Course>().Property(pre => pre.Name).HasColumnName("name");
}

Even if I type the foreign key value for a value that already exists, the added value is the next key total value, as an auto-increment. Is there anything I can do? My treatment function is also not identifying when I submit a Project ID that already exists.

  • Are you using the right Entityframework? If yes, add information about how you are doing this inclusion and updating logic in Dbcontext.

  • I just updated with the context class.

  • that addProject is a method that makes Add in the DbSet<Project>? If it is, it will always create a new ID. You need to create a method also for Update.

  • I’ve put the method in the post now. Is it correct for it to create a new Project ID, but would there be a way for it not to create a new Course ID? Any way to ignore the Course table if nothing is added? My Course table has only Id and Name, and I need to include it in the Project the way it is now, with that "public Course Course { get; set; }". As for my Update, it works the same way as the add method.

  • 1

    @Apparently your project table does not have a relationship with the Course table

1 answer

0

Change your Project class by making explicit the relationship between classes through the foreign key:

public class Project
{
    //
    public Course Course { get; set; }

    [ForeignKey("Course")]
    public int CourseId { get; set; }
}

or

public class Project
{
    //
    [ForeignKey("CourseId")]
    public Course Course { get; set; }

    public int CourseId { get; set; }
}
  • I made the changes according to the first example and created a new Migration followed by an update-database, however the Couse table id is still auto-incremented.

  • Maybe it might be related to the context override method? I added in the post.

Browser other questions tagged

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