我在控制器中有代码,可以将数据从View写入表
这是代码
[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");
}
这是模型
[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; }
}
我需要Interview_Id
我尝试这样做,但它不起作用int id = interview.Interview_Id;
如何将id写入变量?
答案 0 :(得分:2)
如果我理解你的问题是对的。你可能会有这样的事情。
public DbSet<Interview> Interviews {get; set;}
将Interview_Id重命名为Id或InterviewId(无下划线)。
public class Interview
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int InterviewId { get; set;}
// other properties
}
DAL方法。
public int Add(Interview inteview)
{
using(DbContext entities = new DbContext()
{
entities.Interviews.Add(interview);
entities.SaveChanges();
var id = interview.InterviewId;
return id;
}
}
来自您的控制器。
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
Dal dalObj = new Dal();
var inteviewId = dal.Add(interview);
//use this id
}
希望这有帮助。
答案 1 :(得分:0)
你可以试试这个。
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
int id = db.Interview.Max(x=>x.Interview_Id);
return RedirectToAction("Index", "Questions");
}
答案 2 :(得分:0)
检查你的dbml 确保正确设置此属性
AutoSync=AutoSync.OnInsert
完整属性通常像这样
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]