Reputation: 1
I am working on an asp.net mvc 5 web project and I have created a Repository Model class to interact with my database , and I am calling my repository from my action method. For example inside my Post Edit action method I have the following code:-
Repository repository = new Repository();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(SecurityRole Role)
{
try
{
if (ModelState.IsValid)
{
repository.InsertOrUpdateRole(Role);
repository.Save();
return RedirectToAction("Index");
}
}}
And here is the repository model clas:-
public class Repository
{
private TEntities tms = new TEntities();
public void InsertOrUpdateRole(SecurityRole role)
{
role.Name = role.Name.Trim();
if (role.SecurityRoleID == default(int))
{
// New entity
//Code goes here
else
{
t.Entry(role).State = EntityState.Modified;
}
}
So my question is when I pass the object from my action method to my repository, how will Entity Framework treat the object ; will it create another copy inside the repository , or it will be tracking the same object ?. And if entity framework will be working on the same object inside the action method and inside the repository method in the session , so how entity framework keeps tracking the object ?
Second question , what is the best approach to follow; to pass the whole object from action method to repository (as I am currently doing), or instead of that to only pass the object id, and to retrieve the object again inside the repository model something as follow:-
repository.InsertOrUpdateRole(Role.RoleID);
and inside the repository
public void InsertOrUpdateRole(int id)
{
var SecurityRole = t.SecurityRoles.SingleOrDefault(a => a.SecurityRoleID == role.SecurityRoleID);
}
Upvotes: 0
Views: 1535
Reputation: 3402
In C# objects are passed by reference. When you save a new role
in your ActionResult
you notice it has gotten an Id
after the InsertOrUpdateRole
call. EF is starting to track changes as soon something is attached to the context. So your first approach works fine (I use it as well). Make sure the model is passed to the InsertOrUpdateRole
function with all it's values set, EF will overwrite the entire record so if you forget a property in your view it will become an empty value in the database. If you only want to update a few properties of the model use your second approach.
Upvotes: 2