Wow...okay.
First off, while making ViewModels for your data objects is a good idea, you have a direct coupling which is a bit odd. Also, do your data-mapping in the ViewModel Constructor rather than as a handler, because you made a mistake there. You're trying to add a new object that you've already assigned an ID to:
public class TestHandler
{
TestContext db = new TestContext();
public List<TestDTO> GetData()
{
var temp = from s in db.TBL_TEST
select new TestDTO
{
ID = s.ID,
Description = s.DESCRIPTION,
StatusID = s.ID
};
return temp.ToList();
}
public void Insert(TestDTO temp)
{
TBL_TEST s = new TBL_TEST();
s.DESCRIPTION = temp.Description;
s.ID = temp.StatusID;
db.TBL_TEST.Add(s);
db.SaveChanges();
}
}
Instead, use a constructor inject to copy parameters over. For the sake of a later point I'm going to use the TBL_TEST object:
public partial class TBL_TEST
{
public int ID { get; set; }
[Required]
[StringLength(50)]
public string DESCRIPTION { get; set; }
public int STATUS_ID { get; set; }
public virtual TBL_STATUS TBL_STATUS { get; set; }
public TestDTO(CreateTest test)
{
DESCRIPTION = test.Description;
STATUS_ID= test.StatusID
}
}
You're also much better off taking a layer of abstraction or two out of your code, since right now you're using a ViewModel (CreateTest) to create a ViewModel (TestDTO), using an unnecessary handler object, to create a ORM model (TBL_TEST). While I'm all for abstraction, this is needlessly complex. Remember that a DbContext is ALREADY an abstraction layer that implements the Repository pattern. Assigning handlers to it is only useful in an event-driven framework, and MVC is not natively terribly event friendly.
Your current mapping on the context looks fine at first blush, so let's look at just your controller actions. I'm going to strip out the handler because, IMHO, it's extraneous:
public class TestController : Controller
{
protected TestContext _context = new TestContext();
public ActionResult Index()
{
return View(_context.TBL_TEST.ToArray());
}
public ActionResult Details(int id)
{
return View(_context.TBL_TEST.Find(id));
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(CreateTest model)
{
try
{
_context.TBL_TEST.Add(new TBL_TEST(model));
return RedirectToAction("Index");
}
catch
{
return View();
}
}
#region implement IDisposable
protected bool _disposed = false;
protected override void Dispose(bool disposing)
{
if(!_disposed)
{
if(disposing)
{
_context.Dispose();
}
_disposed = true;
}
}
#endregion
}
This construct places management of your context into the Controller, which is where it's really designed to be in MVC. It also links your ViewModel to your ORM object, and vastly simplifies the code.