EF通过界面添加新项目

时间:2014-02-26 16:48:29

标签: c# asp.net-mvc entity-framework

我是MVC和EF的新手,有点纠结我有以下界面:

  public interface IReportDataSource
{
   IQueryable<PostDetail> PostDetails { get; }
   void Save();
}

此数据库上下文:

  public class ReportDb: DbContext, IReportDataSource
{
    public DbSet<PostDetail> PostDetails { get; set; }

    public ReportDb()
        : base("DefaultConnection")
    {
    }

    void IReportDataSource.Save()
    {
        SaveChanges();

    }

    IQueryable<PostDetail> IReportDataSource.PostDetails
    {
        get { return PostDetails; }
    }
}

和这个动作

 [HttpPost]
    public ActionResult PostDetails(PostDetailsViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            //save

          //  var storePost = _db.PostDetails.Single();

            var pd = new PostDetail();
            pd.Grade = viewModel.Grade;
            pd.ContractType = viewModel.SelectedContractType;
            pd.Directorate = viewModel.SelectedDirectorate;
            pd.Division = viewModel.Division;
            pd.HoursPerWeek = viewModel.HoursPerWeek;
            pd.Length = viewModel.SelectedContractLength;
            pd.LineManager = viewModel.LineManager;
            pd.LineManagerContactNumber = viewModel.LineManagerContactNumber;
            pd.PositionTitle = viewModel.PositionTitle;
            pd.Section = viewModel.Section;
            pd.SpecifyDuration = viewModel.SpecifyDuration;
            pd.SpecifyEndDate = viewModel.SpecifyEndDate;

            _db.Save();

            return RedirectToAction("Index", "HomeController");

        }

我想我需要能够通过我的界面调用add来将新的PostDetails对象添加到datacontext中,然后再调用save吗?

1 个答案:

答案 0 :(得分:0)

我认为保存前_db.PostDetails.Add(pd)可以提供帮助