0
我想插入多個表中的數據,但在另一個表中插入時卡住了,部分已經看到了類似的錯誤在其他職位,但沒有什麼工作對我來說,錯誤是: -實體類型StudentDetail是不是該機型爲當前上下文
的實體類型StudentDetail不是型號爲當前上下文的一部分。
Web配置
<connectionStrings>
<add name="ConnectionContext" connectionString="metadata=res://*/Models.Model3.csdl|res://*/Models.Model3.ssdl|res://*/Models.Model3.msl;provider=System.Data.SqlClient;provider connection string="data source=.\MSSQLSERVER2014;initial catalog=Sample;user id=sa;password=**;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
的DbContext類
public class ConnectionContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<StudentDetail> StudentDetails { get; set; }
}
學生模型
public partial class Student
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
}
StudentDetails模型
[Table("StudentDetails")]
public partial class StudentDetail
{
[ForeignKey("FK_SD")]
public int Id { get; set; }
public string Address { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
}
視圖模型
public class StudentViewModel
{
public Student Students { get; set; }
public StudentDetail StudentDetails { get; set; }
}
行動 私人ConnectionContext分貝=新ConnectionContext();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StudentViewModel model)
{
if (ModelState.IsValid)
{
model.Students.CreatedDate = DateTime.Now;
db.Students.Add(model.Students);
db.SaveChanges();
var objstudetails = new StudentDetail
{
Id = model.Students.Id,
Address = "SYDNEY"
};
//Here it breaks stating StudentDetails not a part of model..
db.StudentDetails.Add(objstudetails);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model.Students);
}
夥計們請幫忙 – Dave