oceanicwang / dapper-dot-net

Automatically exported from code.google.com/p/dapper-dot-net
Other
0 stars 0 forks source link

How to handle sqlceconnection when using Dapper with Nancy #113

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
Hi all;

Sorry i am very new to Dapper and Nancy, and I am trying to use Dapper with 
nancy and connecting to SqlCEconnection for data store. I use 
Nancy.ViewEngines.Razor as my view engine. 

I would like to know where should i start to open session (before request) for 
sqlceconnecton, and close session (after request) while my view still can 
render the data respond. 

I use all the latest Dapper and Nancy version.

Thanks you so much for your kind support.

Original issue reported on code.google.com by vuth...@gmail.com on 13 Sep 2012 at 8:31

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
What actually is that when i use Nancy Razor view engine, after i GetList from 
the table to the model, then past it to view it is error when using IEnumerable 
but it works when using List. I think because of the Lazy Loading when i use 
IEnumerable, the connection was closed before render in view. 

// In my DepartmentModule.cs
 Get["/"] = p =>
                   {
                       IEnumerable<Department> department = db.GetList<Department>(); // error
                       IList<Department> department = db.GetList<Department>().ToList();  // work

                       return View["department", department];
                   };

// in BaseModules.cs
public class BaseModule: NancyModule
  {
    public dynamic Model = new ExpandoObject();
    protected IDbConnection db;

    public BaseModule()
    {
      SetupDefaults();      
    }

    public BaseModule(string modulePath): base(modulePath)
    {
      SetupDefaults();
    }

    private void SetupDefaults()
    {
      Before.AddItemToEndOfPipeline(ctx =>
      {
        Model.Master = new MasterModel();
        return null;
      });

      Before += ctx =>
      {
        var conString = System.Configuration.ConfigurationManager.ConnectionStrings["dbString"].ToString();
        db = new SqlCeConnection(conString);
        db.Open();
        return null;
      };

      After.AddItemToEndOfPipeline(ctx =>
      {
        if (db.State == ConnectionState.Open)
          db.Close();
      });
    }
  }

And i am very much appreciated if you can give me the sample of the code. 

Original comment by vuth...@gmail.com on 13 Sep 2012 at 10:49