无法保存对上下文的更改

时间:2012-07-12 11:44:57

标签: c# asp.net-mvc

有人可以帮忙吗?

我的控制器中有创建动作:

  public class MovieController : Controller
  {
      Connect connection = new Connect();
      Movie movie = new Movie();

      [HttpPost]
      public ActionResult Create(Movie moviecreated)
      {
        try
        {
            // TODO: Add insert logic here
            connection.Connection().AddObject(moviecreated);
            connection.Connection().Context.SaveChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            return View(movie);
        }
       }
    }

我的连接类

public class Connect
{
    public ObjectSet<Movie> Connection() 
    { 
        var connStr = ConfigurationManager.ConnectionStrings["Entities"]; 
        ObjectContext context = new ObjectContext(connStr.ConnectionString); 
        var movieContext = context.CreateObjectSet<Movie>(); 
        return movieContext; 
    } 
 }

它没有保存新的添加,我有什么错? 非常感谢。

2 个答案:

答案 0 :(得分:1)

每次调用connection()时,它都会创建另一个实例。一旦你添加了另一个新记录,你就会尝试保存但不同的上下文。 将其更改为属性,以便保存上下文。

答案 1 :(得分:1)

试试这个:

public class MovieController : Controller
{
  private Connect connection;
  private Movie movie;

  public MovieController() 
  {
       this.connection = new Connect();
       this.movie = new Movie();
  }

  [HttpPost]
  public ActionResult Create(Movie moviecreated)
  {
    try
    {
        // TODO: Add insert logic here
        this.connection.MovieContext.AddObject(moviecreated);
        this.connection.MovieContext.Context.SaveChanges();
        return RedirectToAction("Index");
    }
    catch
    {
        return View(movie);
    }
   }
}


public class Connect
{
    private ObjectSet<Movie> movieContext;

    public ObjectSet<Movie> MovieContext 
    {
        get
        {
            if (this.movieContext == null) 
            { 
                this.SetMovieContext(); 
            }

            return this.movieContext;
        }
    }

    public void SetMovieContext() 
    { 
        var connStr = ConfigurationManager.ConnectionStrings["Entities"]; 
        var context = new ObjectContext(connStr.ConnectionString); 
        this.movieContext = context.CreateObjectSet<Movie>(); 
    } 
}
相关问题