Showing posts with label ADO.NET entity Framework. Show all posts
Showing posts with label ADO.NET entity Framework. 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();

Unable to update the EntitySet '' because it has a DefiningQuery and no element exists in the element to support the current operation

Unable to update the EntitySet '' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation

Got the above error when I was writing Code to insert data using EntityDataModel with below code


                Student_Marks sMarks = new Student_Marks();
                sMarks.Student_Id = int.Parse(model.Student_Id);
                sMarks.Marks = int.Parse(model.Marks);
                DBobj.AddToStudent_Marks(sMarks);
                DBobj.SaveChanges();




Solution : I rechecked Table Student_marks in Database and Primary Key was not
set in the table , I set the primary key and above problem was resolved

Code Example ADO.NET Entity Framework "Insert Update Delete" data in MVC application


How we can use ASP.NET MVC Framework check this post

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 Insert and Update Data in Student_Marks table(Student_id,Marks)in One More view
Using ADO.NET Entity framework.

1.) Creating the ADO.NET Entity Data Model 
     Check the below post to create ADO.NET Entity Data Model.

2.) We will Add Our Form AddStudentMarks within the same App
3.)Right click on Models Add new class StudentmarksModel.cs
4.)Code On StudentMarksModel.cs Create property corresponding to each Form Field + Write the Validation 

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;


namespace TestMVCapplication.Models
{
    public class StudentMarksModel
    {


        [DisplayName("Marks")]
        [Required(ErrorMessage = "* Required")]
        public string  Marks { get; set; }


        public string Student_Id { get; set; }


        public IEnumerable<SelectListItem> StudentList { get; set; }


    }
}


5.)We’ll then add a “StudentMarksController.cs” controller class to our project's Controllers folder that exposes two “AddStudentMarks” action methods.  




The first action method is called when an HTTP-GET request comes for the /StudentMarks/Create URL.  It will display a blank form for entering Student data. 
 The second action method is called when an HTTP-POST request comes for the /Studentmarks/Create URL.  It maps the posted form input to a StudentMarks object, verifies that no binding errors occurred, and if it is valid will eventually save it to a database(Business Logic)






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



namespace TestMVCapplication.Controllers
{
    public class StudentMarksController : Controller
    {
        //
        // GET: /StudentMarks/
        [HttpGet]
        public ActionResult AddStudentMarks()
        {
         
          TestMVCEntities3 DBobj = new TestMVCEntities3();

          //ViewData["StudentList"] = new SelectList(DBobj.Student, "Student_Id", "Name");

          
          //return View();

         //To set the Student Names in DropdownList
          var model = new StudentMarksModel();
          model.StudentList = new SelectList(DBobj.Student, "Student_Id", "Name");
               
                          
           return View(model);
            
        }



        [HttpPost]

        public ActionResult AddStudentMarks(StudentMarksModel model)
        {
           //Add Data Using Entity Framework in ADO.NET

            TestMVCEntities3 DBobj = new TestMVCEntities3();

            int StudentId = Convert.ToInt32(model.Student_Id);


            //Check If the reord exists with the Dropdownlist selcted value as Student_Id
            var record = DBobj.Student_Marks.FirstOrDefault(m => m.Student_Id == StudentId);
            
            //If record exists update it with the value entered in marks textbox
            if (record != null)
            {
                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();

            }

            //If record doesn't exists Insert the new record
            else
            {
                Student_Marks sMarks = new Student_Marks();

                sMarks.Student_Id = int.Parse(model.Student_Id);
                sMarks.Marks = int.Parse(model.Marks);



                DBobj.AddToStudent_Marks(sMarks);
                DBobj.SaveChanges();
            }


            //To set the Student Names in DropdownList
            var modelsend = new StudentMarksModel();
            modelsend.StudentList = new SelectList(DBobj.Student, "Student_Id", "Name");


            return View(modelsend);
           
        }

    }
}

7.)After we’ve implemented our controller, we can right-click within one of its action methods and choose the “Add View” command within Visual Studio – which will bring up the “Add View” dialog
Add  AddStudentMarks.aspx view file for us under the \Views\StudentMarks\ 
8.)Design the form on AddStudentMarks.aspx using HTMlHelper Class



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


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


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


    <h2>AddStudentMarks</h2>


<form id="form1" runat="server">
<% Html.EnableClientValidation(); %> 
    <% using (Html .BeginForm() ){%>
        <%= Html.ValidationSummary(true, "A few fields are still empty") %>
     <fieldset>
           <div class="editor-field">
                <%= Html.DropDownListFor(x => x.Student_Id,Model.StudentList)%>
                <%= Html.ValidationMessageFor(m => m.Student_Id) %>
           </div>
            
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Marks) %>
                <%= Html.ValidationMessageFor(m => m.Marks) %>
            </div>
             <p>
                <input type="submit" value="Submit" />
            </p>
        </fieldset>
        <p id="result"><%=TempData["Message"] %></p>
    <% } %>
    </form>
</asp:Content>


9)Add The link for Student in Site.Master



10) Run the app
11.)Click StudentMarks

      StudentList will be filled up from Student table in DropDownlist
     

12)select the name and insert Marks if The student_id already Exists in Student_Marks It will 
   update the record if it does not exist it will add new record with the selected Student_Id from drop Down and input marks

13.) See the Updated Record in DB

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