locked
Value cannot be null parameter name Entity RRS feed

  • Question

  • User-1707626336 posted

    hello everyone,

    I am currently practicing web api parsing in .net core and displaying them in angular.

    I am having an error whenever i try to save data into the database

    context class
    
    using System;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Metadata;
    
    namespace studdetail.Models
    {
        public partial class swagapiContext : DbContext
        {
            public swagapiContext()
            {
            }
    
            public swagapiContext(DbContextOptions<swagapiContext> options)
                : base(options)
            {
            }
    
            public virtual DbSet<Stulogin> Stulogin { get; set; }
            public virtual DbSet<Tbstudent> Tbstudent { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                    optionsBuilder.UseSqlServer("Data Source=LAPTOP-5KE9QV2J\\SQLEXPRESS;Initial Catalog=swagapi;Integrated Security=True");
                }
            }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Stulogin>(entity =>
                {
                    entity.HasKey(e => e.Uname)
                        .HasName("PK__tmp_ms_x__C7D2484FBAE19509");
    
                    entity.ToTable("stulogin");
    
                    entity.Property(e => e.Uname)
                        .HasColumnName("uname")
                        .HasMaxLength(20)
                        .IsUnicode(false);
    
                    entity.Property(e => e.Upass)
                        .HasColumnName("upass")
                        .HasMaxLength(50)
                        .IsUnicode(false);
    
                    entity.HasOne(d => d.UnameNavigation)
                        .WithOne(p => p.StuloginUnameNavigation)
                        .HasPrincipalKey<Tbstudent>(p => p.Stuname)
                        .HasForeignKey<Stulogin>(d => d.Uname)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK__stulogin__uname__4D94879B");
    
                    entity.HasOne(d => d.UpassNavigation)
                        .WithMany(p => p.StuloginUpassNavigation)
                        .HasPrincipalKey(p => p.Stupass)
                        .HasForeignKey(d => d.Upass)
                        .HasConstraintName("FK__stulogin__upass__4E88ABD4");
                });
    
                modelBuilder.Entity<Tbstudent>(entity =>
                {
                    entity.HasKey(e => e.Stuid);
    
                    entity.ToTable("tbstudent");
    
                    entity.HasIndex(e => e.Stuname)
                        .HasName("UQ__tmp_ms_x__B4E7C00E4B16F077")
                        .IsUnique();
    
                    entity.HasIndex(e => e.Stupass)
                        .HasName("UQ__tmp_ms_x__05586DDA0FE3BDF8")
                        .IsUnique();
    
                    entity.Property(e => e.Stuid).HasColumnName("stuid");
    
                    entity.Property(e => e.Stuage).HasColumnName("stuage");
    
                    entity.Property(e => e.Stucls)
                        .HasColumnName("stucls")
                        .HasMaxLength(5)
                        .IsUnicode(false);
    
                    entity.Property(e => e.Stunam)
                        .HasColumnName("stunam")
                        .HasMaxLength(50)
                        .IsUnicode(false);
    
                    entity.Property(e => e.Stuname)
                        .IsRequired()
                        .HasColumnName("stuname")
                        .HasMaxLength(20)
                        .IsUnicode(false);
    
                    entity.Property(e => e.Stupass)
                        .IsRequired()
                        .HasColumnName("stupass")
                        .HasMaxLength(50)
                        .IsUnicode(false);
                });
    
                OnModelCreatingPartial(modelBuilder);
            }
    
            partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
        }
    }
    
    main class
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace studdetail.Models
    {
        public partial class Tbstudent
        {
            public Tbstudent()
            {
                StuloginUpassNavigation = new HashSet<Stulogin>();
            }
    
            public int Stuid { get; set; }
            [Display(Name = "Name")]
            [Required(ErrorMessage = "Enter Name")]
            public string? Stunam { get; set; }
            [Display(Name = "Age")]
            [Required(ErrorMessage = "Enter Age")]
            public int? Stuage { get; set; }
            [Display(Name = "Class")]
            [Required(ErrorMessage = "Enter Class")]
            public string? Stucls { get; set; }
            [Display(Name = "Student User Name")]
            [Required(ErrorMessage = "Enter Student User Name")]
            [RegularExpression(@"^[0-9a-zA-Z''-'\s]{1,40}$", ErrorMessage = "special characters are not  allowed.")]
            public string? Stuname { get; set; }
            [Required]
            [DataType(DataType.Password)]
            [Display(Name = "Enter Password")]
            public string? Stupass { get; set; }
    
            public virtual Stulogin StuloginUnameNavigation { get; set; }
            public virtual ICollection<Stulogin> StuloginUpassNavigation { get; set; }
        }
    }
    
    Data access layer
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.EntityFrameworkCore;
    
    namespace studdetail.Models
    {
        public class StudentDataAccessLayer :swagapiContext
        {
            swagapiContext obj = new swagapiContext();
            public IEnumerable<Tbstudent> getStudents()
            {
                try
                {
                    return obj.Tbstudent.ToList();
                }
                catch
                {
                    throw;
                }
            }
            //Add student
            public Int32 AddStudent(Tbstudent tbstudent)
            {
                try
                {
                    obj.Tbstudent.Add(tbstudent);
                    obj.SaveChanges();
                    return 1;
                }
                catch
                {
                    throw;
                }
            }
            //Update student details
            public Int32 UpdateStudent(Tbstudent tbstudent)
            {
                try
                {
                    obj.Entry(tbstudent).State = EntityState.Modified;
                    obj.SaveChanges();
    
                    return 1;
                }
                catch
                {
                    throw;
                }
            }
            //View student details
            public Tbstudent GetStudentData(int id)
            {
                try
                {
                    Tbstudent tbstudent = obj.Tbstudent.Find(id);
                    return tbstudent;
                }
                catch
                {
                    throw;
                }
            }
            //Delete student details
            public Int32 DeleteStudent(int id)
            {
                try
                {
                    Tbstudent s = obj.Tbstudent.Find(id);
                    obj.Tbstudent.Remove(s);
                    obj.SaveChanges();
                    return 1;
                }
                catch
                {
                    throw;
                }
            }
        }
    }
    
    angular services
    
    import { Inject, Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse, HttpHandler } from '@angular/common/http';
    import { Route, Router } from '@angular/router';
    import { throwError, Observable } from 'rxjs';
    import { map, catchError } from 'rxjs/operators';
    import { StudentData } from '../Student';
    
    @Injectable({
        providedIn: 'root'
    })
    export class StudentService {
        url: string = " ";
        constructor(private _http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
            this.url = baseUrl;
        }
        getStudent(): Observable<StudentData[]> {
            return this._http.get<StudentData[]>(this.url + 'api/Student/Index');
            
        }
        addStudent(student: StudentData): Observable<StudentData[]> {
            return this._http.post<StudentData[]>(this.url + 'api/Student/Create', student);
        }
        getStudentById(id: number): Observable<StudentData[]> {
            return this._http.get<StudentData[]>(this.url + 'api/Student/Details/' + id);
                
        }
        updateStudent(student: StudentData): Observable<StudentData[]> {
            return this._http.put<StudentData[]>(this.url + 'api/Student/Edit', student);
        }
        deleteStudent(id: number): Observable<number> {
            return this._http.delete<number>(this.url + 'api/Student/Delete/' + id);
               
        }
        errorHandler(error: Response) {
            return throwError(error);
        }
    }
    
    add student component and html
    
    import { Inject, Injectable, Component, OnInit } from '@angular/core';
    import { HttpClient, HttpErrorResponse, HttpClientModule, HttpEvent } from '@angular/common/http';
    import { FormBuilder, FormControl, FormGroup, NgForm, Validators, FormsModule } from '@angular/forms';
    import { Route, Router, ActivatedRoute } from '@angular/router';
    import { FetchStudentComponent } from '../fetchstudent/fetchstudent.component';
    import { StudentService } from '../../../app/Services/studentservice';
    import { StudentData } from '../../Student';
    
    @Component({
        selector: 'addstudent',
        templateUrl: './addstudent.component.html'
    })
    
    export class AddStudent implements OnInit {
        studentForm: FormGroup;
        title: string = "Create";
        stuid: number;
        errorMessage: any;
        constructor(private _fb: FormBuilder, private _avRoute: ActivatedRoute, private _studentservice: StudentService, private _router: Router) {
            if (this._avRoute.snapshot.params["stuid"]) {
                this.stuid = this._avRoute.snapshot.params["stuid"];
            }
            this.studentForm = this._fb.group({
                stuid: 0,
                stunam: ['', [Validators.required]],
                stuage: ['', [Validators.required]],
                stucls: ['', [Validators.required]],
                stuname: ['', [Validators.required]],
                stupass: ['', [Validators.required]],
            })
        }
        ngOnInit() {
            if (this.stuid > 0) {
                this.title = "Edit";
                this._studentservice.getStudentById(this.stuid).subscribe(data => this.studentForm.setValue(data), error => this.errorMessage = error);
            }
        }
        save() {
            if (!this.studentForm.valid) {
                return;
            }
            if (this.title == "Create") {
                this._studentservice.addStudent(this.studentForm.value).subscribe((data) => {
                    this._router.navigate(['/fetch-student']);
                }, error => this.errorMessage = error)
            } else if (this.title == "Edit") {
                this._studentservice.updateStudent(this.studentForm.value).subscribe((data) => {
                    this._router.navigate(['/fetch-student'])
                }, error => this.errorMessage = error)
            }
        }
        cancel() {
            this._router.navigate(['/fetch-student']);
        }
        get stunam() {
            return this.studentForm.get('stunam');
        } get stuage() {
            return this.studentForm.get('stuage');
        }get stucls() {
            return this.studentForm.get('stucls');
        }get stuname() {
            return this.studentForm.get('stuname');
        }get stupass() {
            return this.studentForm.get('stupass');
        }
    }
    
    
    
    
    Html
    
    
    
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <form class="form" [formGroup]="studentForm" (ngSubmit)="save()" #formDir="ngForm" novalidate>
      <table border="1">
        <tr>
          <td>Student Name</td>
          <td><input type="text" class="form-control" formControlName="stunam" /></td>
        </tr>
        <tr>
          <td>Student Age</td>
          <td><input type="text" class="form-control" formControlName="stuage" /></td>
        </tr>
        <tr>
          <td>Student Class</td>
          <td><input type="text" class="form-control" formControlName="stucls" /></td>
        </tr>
        <tr>
          <td>Student User Name</td>
          <td><input type="text" class="form-control" formControlName="stuname" /></td>
        </tr>
        <tr>
          <td>Student Password</td>
          <td><input type="password" class="form-control" formControlName="stupass" /></td>
        </tr>
        <tr>
          <td colspan="2">
            <button type="submit" class="btn btn-primary" >Save</button>
            <button class="btn btn-danger" (click)="cancel()">Cancel</button>
          </td>
        </tr>
      </table>
    </form>
    </body>
    </html>
    
    fetch student component and html
    
    
    html
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title>STUDENT DETAILS</title>
    </head>
    <body>
      <p> <a [routerLink]="['/add-student']">Create New Student Details</a> </p>
      <table border="1" *ngIf="stuList">
        <thead style="background-color:green;font-weight:bold;color:white;">
          <tr>
            <th>Student ID</th>
            <th>Name</th>
            <th>Age</th>
            <th>Class</th>
            <th>Username</th>
            <th>Password</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let s of stuList">
            <td>{{s.stuid}}</td>
            <td>{{s.stunam}}</td>
            <td>{{s.stuage}}</td>
            <td>{{s.stucls}}</td>
            <td>{{s.stuname}}</td>
            <td>{{s.stupass}}</td>
            <td><a [routerLink]="['/Student/Edit/', s.stuid]">Edit</a> | <a [routerLink]="" (click)="delete(s.stuid)">Delete</a></td>
          </tr>
        </tbody>
      </table>
    </body>
    </html>
    
    
    component
    
    
    
    import { Inject, Injectable, Component } from '@angular/core';
    import { HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpHeaders, HttpClientModule } from '@angular/common/http';
    import { Route, Router, ActivatedRoute } from '@angular/router';
    import { FormBuilder, FormGroup, FormsModule } from '@angular/forms';
    import { throwError } from 'rxjs';
    import { map, catchError } from 'rxjs/operators';
    import { StudentService } from '../../Services/studentservice';
    
    @Component({
        selector: 'fetchstudent',
        templateUrl: './fetchstudent.component.html'
    })
    export class FetchStudentComponent {
        public stuList : StudentData[];
        constructor(public _http: HttpClient, private _router: Router, private _studentservice: StudentService) {
            this.getStudent();
        }
        getStudent() {
            this._studentservice.getStudent().subscribe((data) => {
                this.stuList = data
            });
        }
        delete(id: number) {
            var q = confirm("Do you want to delete student detail" + id);
            if (q) {
                this._studentservice.deleteStudent(id).subscribe((data) => {
                    this.getStudent();
                }, error => console.error(error))
            }
        }
    }
    interface StudentData {
        stuid: number;
        stunam: string;
        stuage: number;
        stucls: string;
        stuname: string;
        stupass: string;
    }
      any kind of help will be appreciated 
    Thursday, March 12, 2020 12:03 PM

All replies