Reputation: 336
I am using Entity Framework with MVC structure for a project of mine.
As EF manages all database related changes and on "Update Model From Database" we are getting up to date model.
So Do I need to create Separate model.cs class for each of my Table to Use it as a object and Set Value into that.
To be more specific, The whole project is having all operations using Ajax call. In those Ajax call I am passing values to data in a JSON from.
Now, At controller level I need to retrieve the value from that JSON.
For that How Can I use my Entity Model for particular Table ?
Do I need to create model for every table ?
Can't Models be generated for each table automatically?
Updated: Reference Code Added.
1.
Let's say
I have a table Student with , StudentID INT, ClassID INT , Name VARCHAR().
2.
Here is the JavaScript Code
function AddStudent() {
var data = { "ClassID": 1, "Name": 'ABC' }
$.ajax({
url: '/Admin/AddNewStudent',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
data: JSON.stringify(data),
success: function (ServiceResponce) {
refreshgird();
}
});
}
3.
StudentController.cs
public JsonResult AddNewStudent(Student obj)
{
try
{
var add = db.AddNewStudent(obj.ClassID, obj.Name).ToString();
return Json(add, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
4. Student.cs
public class Student
{
public int ClassID{ get; set; }
public string Name{ get; set; }
}
My question is by creating Student.cs model I am following correct way or not ?
Upvotes: 0
Views: 1803
Reputation: 176
If your EF model is included in the MVC project I would say no you do not have to create separate models for each entity - just use the ones created by EF.
If your MVC project is split into a Data, Domain and Presentation layers (projects) you can separate the generated data classes from the EDMX (in the Data layer) and have them generated in the Domain layer. See Plural Sight training by Julie Lerman "Getting Started with Entity Framework 5" "Separating Generated Domain Classes from the EDMX file" chapter.
If you are a purist then you should have at least 3 layers (Data, Domain and Presentation) and the Domain objects should not be the ones generated by EF. They should be customized to the applications needs and loaded from the EF objects as required.
Upvotes: 1