In this article, I will explore entity framework with ASP.NET MVC. We will modify Form validation sample that will access data layer using entity framework.
We will create the following table in local database using SQL express.
CREATE TABLE [dbo].[tblComment](
[CommentID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Email] [nvarchar](100) NULL,
[Comment] [nvarchar](100) NULL)
Now, Right click on the Models directory and select add new item. In the dialog select ADO.NET Entity Data Model as shown below.
In the wizard, select "Generate from Database" and then select your database connection string. Then select the tblComment table and the click finished. Visual Studio will create a set of .NET classes that are custom built for accessing database as shown below.
Now, we will modify our controller as shown below.
[HandleError]
public class UserCommentController : Controller
{
[AcceptVerbs("GET")]
public ActionResult UserComment()
{
return View();
}
[AcceptVerbs("POST")]
public ActionResult UserComment(string name, string email, string comment)
{
ViewData["name"] = name;
ViewData["email"] = email;
ViewData["comment"] = comment;
if (string.IsNullOrEmpty(name))
ModelState.AddModelError("name", "Please enter your name!");
if (!string.IsNullOrEmpty(email) && !email.Contains("@"))
ModelState.AddModelError("email", "Please enter a valid e-mail!");
if (string.IsNullOrEmpty(comment))
ModelState.AddModelError("comment", "Please enter a comment!");
if (ViewData.ModelState.IsValid)
{
// Add to database
try
{
CommentEntities _db = new CommentEntities ();
tblComment commentToCreate = new tblComment();
commentToCreate.Name = name;
commentToCreate.Email = email;
commentToCreate.comment= comment;
_db.AddTotblComment(commentToCreate);
_db.SaveChanges();
}
catch
{
return View();
}
}
return View();
}
}
Summary
In this article, we explored entity framework with asp.net MVC. In Next article, I will explore Custom IDataErrorInfo Interface.
CodeProject