我扩展了一个实体框架类(SQL服务器表),并为子类添加了一些额外的属性,但是当我想插入已经扩展的表时,我得到了这个异常:
无法找到EntityType'Student.Models.Add.SubjectToStageModel'的映射和元数据信息。
我的控制器:
[HttpPost]
public ActionResult SubjectToStage(SubjectToStageModel model)
{
try
{
if (ModelState.IsValid)
{
using (StudentEntities studentEntities = new StudentEntities())
{
int intCount =
studentEntities.SubjectToStageTbls.Count(
x => x.StageId == model.StageId && x.SubjectId == model.SubjectId);
if (intCount == 0)
{
studentEntities.SubjectToStageTbls.Add(model);
studentEntities.SaveChanges();
}
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.ToString());
TempData["error"] = "An error occured";
}
return RedirectToAction("SubjectToStage");
}
我的基类:
public partial class SubjectToStageTbl
{
public SubjectToStageTbl()
{
this.StudentMarkTbls = new HashSet<StudentMarkTbl>();
}
public int SubjectToStageId { get; set; }
public int SubjectId { get; set; }
public int StageId { get; set; }
public int Point { get; set; }
public virtual StageTbl StageTbl { get; set; }
public virtual ICollection<StudentMarkTbl> StudentMarkTbls { get; set; }
public virtual SubjectTbl SubjectTbl { get; set; }
}
我的子类:
public class SubjectToStageModel : SubjectToStageTbl
{
public IEnumerable<SelectListItem> StageListItem
{
get
{
List<SelectListItem> listsSelectListItems = new List<SelectListItem>();
try
{
using (StudentEntities studentEntities = new StudentEntities())
{
IQueryable<StageTbl> queryableStage = studentEntities.StageTbls;
foreach (var stage in queryableStage)
{
SelectListItem selectListItem = new SelectListItem();
selectListItem.Value = stage.StageId.ToString();
selectListItem.Text = stage.StageName;
listsSelectListItems.Add(selectListItem);
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.ToString());
}
return listsSelectListItems;
}
}
public IEnumerable<SelectListItem> SubjectListItem
{
get
{
List<SelectListItem> listsSelectListItems = new List<SelectListItem>();
try
{
using (StudentEntities studentEntities = new StudentEntities())
{
IQueryable<SubjectTbl> queryableSubject = studentEntities.SubjectTbls;
foreach (var stage in queryableSubject)
{
SelectListItem selectListItem = new SelectListItem();
selectListItem.Value = stage.SubjectId.ToString();
selectListItem.Text = stage.SubjectName;
listsSelectListItems.Add(selectListItem);
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.ToString());
}
return listsSelectListItems;
}
}
}
答案 0 :(得分:1)
您没有明确映射SubjectToStageModel
类。如果您希望Entity Framework使用派生类,您也应该将它们添加到模型中。但我不认为你打算首先这样做。
实际上,SubjectToStageModel
是一个视图模型。从实体类派生视图模型看起来很方便,但我认为通常它并不是一个好主意。视图模型应根据他们使用的视图(或用例)进行定制。有几个原因:
也许这些考虑因素并不适用于您的情况。我还是喜欢拥有一个独立的视图模型。但是,如果你很懒(我们开发人员更喜欢单词实用主义),你可能会成功:
studentEntities.SubjectToStageTbls.Add((SubjectToStageTbl)model);
(我从未尝试过)。