我可以返回这个:context.CreateObjectSet <movie>()?</movie>

时间:2012-07-12 09:36:43

标签: c#

我添加了一个名为Connect.cs的类;

namespace MovieApp.DAL
{
   public class Connect
   {
      public Connection()  //my class needs to have a return type
      {
        var connStr = ConfigurationManager.ConnectionStrings["Entities"];
        ObjectContext context = new ObjectContext(connStr.ConnectionString);
        var movieContext = context.CreateObjectSet<Movie>();
        return movieContext;
      }
   }
}

然后我在我的控制器类中:

namespace MovieApp.Controllers
{
    public class MovieController : Controller
    {
        public ActionResult Index()
       {
        Connect connection = new Connect(//and what will i put here??);
        var movies = connection.OrderBy(m => m.Title);
        return View(movies);
        }
}

显然我得到错误,因为我不知道该怎么做。 movieContext会是什么类型的? 如何让这段代码工作? 谢谢!

3 个答案:

答案 0 :(得分:0)

“Connection”方法的返回类型应该是“context.CreateObjectSet<Movie>()”方法调用的返回类型;这是ObjectSet<Movie>

答案 1 :(得分:0)

这样的东西?

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

然后在你的控制器中:

public ActionResult Index()
{
    Connect connection = new Connect();
    var movies = connection.Connection().OrderBy(m => m.Title);
    return View(movies);
}

答案 2 :(得分:0)

您的代码存在的问题是您没有指定Connection方法的返回类型。即public Connection()应为public ObjectSet<T> Connection<T>()

你可以尝试这样的东西(用记事本写的代码,这只是为了证明这个想法)

public class ObjectContextManager
{
    public ObjectSet GetSet<T>()  
    {
        var connStr = ConfigurationManager.ConnectionStrings["Entities"];
        ObjectContext context = new ObjectContext(connStr.ConnectionString);
        return context.CreateObjectSet<T>();
    }
}

然后将管理器注入控制器并从那里解析所需的集合。不要忘记将数据库对象包装到using块中,以便自动调用Dispose

public class MovieController : Controller
{
    private ObjectContextManager ctxManager;

    public MovieController(ObjectContextManager ctxManager)
    {
        this.ctxManager = ctxManager;
    }

    public ActionResult Index()
    {
        using(var ctx = ctxManager.GetSet<Movie>())
        {
            var movies = ctx.OrderBy(m => m.Title);
            return View(movies);
        }
    }
}