Entity Framework

From MidrangeWiki
Jump to: navigation, search

The Entity Framework is one of the latest methodologies of interacting with a database in .NET. The only problem is that there is not a way for Visual Studio to create these connections to the IBM i automatically. Therefore you must create these classes yourself. Below is a sample object for setting up the entity framework. The example I have is using the new MVC layout for ASP.NET.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IBM.Data.DB2.iSeries;
using System.Data;

namespace MVC.Models
{
    public class ClassName
    {
        private const string _CONNSTRING = "DataSource=xxx.xxx.xxx.xxx;DefaultCollection=LIBRARY;Naming=sql;UserID=USERID;Password=PASSWORD;";
        
        public ClassName()
        {
        }

        public List<DataStructure> GetMethod1()
        {
            DataTable dt = new DataTable();
            using (iDB2Connection conn = new iDB2Connection(_CONNSTRING))
            {
                using (iDB2Command cmd = new iDB2Command("sql statement", CommandType.Text, conn))
                {
                    using (iDB2DataAdapter da = new iDB2DataAdapter(cmd))
                    {
                        da.Fill(dt);
                    }
                }
            }
            var Results = from i in dt.AsEnumerable() select ...; // finish with LINQ-like syntax
            List<DataStructure> results = Results.ToList();
            return results;
        }
    }
}

namespace MVC.Models
{
    public class DataStructure
    {
        public string id { get; set; }
        public string title { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Display()
        {
            var db = new Models.ClassName();
            return View(db.GGetMethod1());
        }
    }
}


Categories