Eugene Sukhomlin Eugene Sukhomlin -4 years ago 121
ASP.NET (C#) Question

Get Id of inserted data (ASP.NET)

I have code in controller that write data from View to table

Here is code

[HttpGet]
public ActionResult WelcomeScreen()
{
// Формируем список команд для передачи в представление
SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
ViewBag.Teams = teams;
SelectList teams2 = new SelectList(db.Companies, "CompanyID", "CompanyName");
ViewBag.Teams2 = teams2;
return View();
}


[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
int id = interview.Interview_Id;
return RedirectToAction("Index", "Questions");
}


Here is model

[Key]
public int Interview_Id { get; set; }
public string Greeting { get; set; }
public string Detail { get; set; }
public Nullable<int> VacancyId { get; set; }

public virtual Vacancy Vacancy { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Interwier> Interwiers { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<InvitationMail> InvitationMails { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MassLink> MassLinks { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<QuestionBlock> QuestionBlocks { get; set; }
}


I need to have
Interview_Id


I try to make it like this, but it not works
int id = interview.Interview_Id;


How I can write id to variable?

Answer Source

If I understood your question right. You might have something like this.

public DbSet<Interview> Interviews {get; set;}

Rename Interview_Id to simply Id or InterviewId (no underscore).

public class Interview
{
 [Key]
 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
 public int InterviewId { get; set;}
 // other properties 
 }

DAL Method.

public int Add(Interview inteview)
{
     using(DbContext entities = new DbContext()
     {
         entities.Interviews.Add(interview);
         entities.SaveChanges();
         var id = interview.InterviewId; 

        return id;
     }

}

From your Controller.

[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
   Dal dalObj = new Dal();
   var inteviewId = dal.Add(interview);
   //use this id
}

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download