Showing posts with label LINQ TO Entity. Show all posts
Showing posts with label LINQ TO Entity. Show all posts

May 18, 2011

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.

I got the above error in the code bellow.
   
                Student_Marks e = (from e1 in DBobj.Student_Marks
                where e1.Student_Id == Convert.ToInt32(model.Student_Id)
                select e1).First();
                e.Marks = int.Parse(model.Marks);
                DBobj.SaveChanges();


 Note: model.Student_Id is string in the above code           

 If you use Convert.ToInt32(“ID”) in the Where clause the upper Exception is thrown.
Solution is to declare a variable of type int, which contains the converted value and use this variable in the Where query.


So I changed the code in the below manner and it worked.


         int StudentId = Convert.ToInt32(model.Student_Id);
         Student_Marks e = (from e1 in DBobj.Student_Marks
         where e1.Student_Id == StudentId
         select e1).First();
         e.Marks = int.Parse(model.Marks);
         DBobj.SaveChanges();

May 14, 2011

ASP.Net MVC Sample Application using ADO.Net Entity Framework

How we can use ASP.NET MVC Framework check this post
http://www.dotnetissues.com/2011/04/code-example-for-aspnet-mvc20.html

In the above Post example I have used ADO.NET to insert the data in SQLServer Db (Student Table)
Now In this post I 'll add one more view Where To Select the records from the above table I 'll
use ADO.NET Entity framework.

1.)Creating the ADO.NET Entity Data Model
In order to use the Entity Framework, you need to create an Entity Data Model. You can take advantage of the Visual Studio Entity Data Model Wizard to generate an Entity Data Model from a database automatically.
Follow these steps:


1)Right-click the Models folder in the Solution Explorer window and select the menu option Add, New Item.
2)In the Add New Item dialog, select the Data category
3)Select the ADO.NET Entity Data Model template, give the Entity Data Model the name Model1.edmx,
4)Click the Add button. Clicking the Add button launches the Data Model Wizard.
5)In the Choose Model Contents step, choose the Generate from a database option and click theNext button



6)In the Choose Your Data Connection step, select the MoviesDB.mdf database connection, enter the entities connection settings name TestMVEntities3, and click the Next button


8)In the Choose Your Database Objects step, select the TestMVC database table and click the Finishbutton


After you complete these steps, the ADO.NET Entity Data Model Designer (Entity Designer) opens.
Model1.designer.cs will be automatically generated and It will Map the Database and the tables as the
entity classes and To Communicate with the DB now we can Communicate with The entity classes objects
We can use EntitySQl query syntax or LINQ to Sql Below is the code sample for both.

To Select Records from student table using entity sql I added below highlighted code in StudentController.cs

Controllers/StudentController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestMVCapplication.Models;
using System.Data;
using System.Data.SqlClient;
using System.Data .Objects ;


namespace TestMVCapplication.Controllers
{
    public class StudentController : Controller
    {
        SqlConnection connObj = new SqlConnection();
        DataSet ds;
        SqlCommand objCommand;
        SqlDataAdapter objAdapter;




        
        // GET: /Student/
        public ActionResult GetStudent()
        {
            return View();
        }




        public ActionResult Viewstudent()
        {


            TestMVCEntities3 DBobj = new TestMVCEntities3();
               
             
                    //ENTITY SQL QUERY SYNTAX
                    ObjectQuery query = DBobj.CreateQuery<Student>("Select value s from student as s");
                    var res = query.Execute(MergeOption.NoTracking) as IEnumerable<Student>;
                    int i=0;
                    foreach (Student  c in res)
                    {
                      // Response .Write (c.Name);
                       ViewData["name"+i.ToString()] = c.Name;
                       ViewData["email" + i.ToString()] = c.Email;
                       ViewData["comment" + i.ToString()] = c.Comment;
                       i++;
                    }




                     //LINQ TO ENTITY QUERY
                     //var query1 = from Student  c in DBobj.Student
                     //               select c;


                     //foreach (Student  c in query1)
                     //       {
                     //          Response .Write (c.Name);
                     //       }


            return View();
        }


        
        [HttpPost]


        public ActionResult GetStudent(StudentModel model)
        {
            Response.Write(model.Name + model.Comment + model.Email);
            //code to insert data in DB using ADO.NET
            connObj.ConnectionString = "Data Source=.\\sqlexpress;Initial Catalog=TestMVC;Integrated Security=True";
         connObj.Open();
        SqlCommand comm = new SqlCommand("insert into student(name,email,comment) values(@name,@email,@comment)", connObj);
        
            comm.Parameters.Add("@name", SqlDbType.VarChar , 50).Value =model .Name ;
            comm.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = model.Comment;
            comm.Parameters.Add("@comment", SqlDbType.VarChar, 50).Value = model.Email;


        int result = comm.ExecuteNonQuery();
        if (result != 0)
            Response.Write(" added");
        else
            Response.Write("Error");


            return View();
        }


    }


    
}




From the above Viewstudent I selected records from the Student Table and 
Inserted those iv ViewData to able to access them in the Viewstudent View
I added one View named Viewstudent.aspx in in views/Student




views/student/Viewstudent.aspx


<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>


<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Viewstudent
</asp:Content>


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">


    <h2>Viewstudent</h2>
   <% for (int i = 0; i <= ViewData.Count;i++ )
      { %>


     Name: <%= ViewData ["name"+i.ToString ()]%>
    <br />
     Email:<%= ViewData ["email"+i.ToString ()]%>
    <br />
     Comment:<%= ViewData ["comment"+i.ToString ()]%>
    <br />
     
        <hr />
<% } %>

</asp:Content>


To Link this View in Previous MVC Example's view I added the below highlighted line of code there 

Views/Student/GetStudent.aspx


<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestMVCapplication.Models.StudentModel>" %>




<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 GetStudent
</asp:Content>




<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">




    <form id="form1" runat="server">




    <h2>GetStudent</h2>




 <% Html.EnableClientValidation(); %> 
    <% using (Html .BeginForm() ){%>
        <%= Html.ValidationSummary(true, "A few fields are still empty") %>
       <%= Html.ActionLink("ViewstudentData", "Viewstudent", "Student")%>
&nbsp;<fieldset>
             <legend>Student Detail</legend>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Name) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Name) %>
                <%= Html.ValidationMessageFor(m => m.Name) %>
            </div>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Email) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Email) %>
                <%=Html.ValidationMessageFor(m => m.Email) %>
            </div>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Comment) %>
            </div>
            <div class="editor-field">
                <%= Html.TextAreaFor(m => m.Comment, 10, 25, null) %>
                <%= Html.ValidationMessageFor(m => m.Comment) %>
              
            </div>
            <p>
                <input type="submit" value="Submit" />
            </p>
        </fieldset>
        <p id="result"><%=TempData["Message"] %></p>
    <% } %>
    </form>
</asp:Content>


Now Run the application again and Click On Student Menu Link




Click On ViewStudentData Link
and you ll get the selected records in the view