Reputation: 4976
I am trying to insert a record using Link to SQL. I know I need to create a new object that includes the column data to be submitted. But How do I identify that object name?
I am successfully able to delete the record, but not able to insert record as I am not able to create a new "student" object
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Student.Models;
namespace Student.Controllers
{
public class StudentController : Controller
{
//
// GET: /Student/
private IStudentRepository _repository;
public StudentController() : this(new StudentRepository())
{
}
public StudentController(IStudentRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.ListAll());
}
public ActionResult RemoveStudent(int id)
{
StudentDataContext student= new StudentDataContext();
var std = student.Students.Single(h => h.StudentID == id);
student.Students.DeleteOnSubmit(std);
student.SubmitChanges();
return Content("Student " + id + " Removed");
}
public ActionResult AddStudent(int studentID)
{
StudentDataContext student= new StudentDataContext();
var std = student.Students.FirstOrDefault(h => h.StudentID == studentID);
if (std == null || std.StudentID < 1)
{
student.Students.InsertOnSubmit(std);
student.SubmitChanges();
return Content("Student " + id + " Added");
}
return Content("Student " + studentID + " is already present");
}
Thanks in Advance
Upvotes: 0
Views: 147
Reputation: 28728
You need to create a new Student()
- or whatever the name of your object is.
if (std == null || std.StudentID < 1)
{
// create a new student before trying to insert
std = new Student() { StudentID = id };
student.Students.InsertOnSubmit(std);
student.SubmitChanges();
return Content("Student " + id + " Added");
}
From my reading your question is
But How do I identify that object name?
i.e. "what is the name of the class?"
You can see this on the LINQ-to-SQL designer. The name of the class is the same as the name of the object on the designer which describes the table. The default name for the class is the same as the table - but if it clashes with another class of that name, then it will be renamed to Student1
.
Upvotes: 1