Is it ok to write EF queries in a separate class file inside models folder instead of writing it in controller itself.
Because I've seen in msdn writing all EF queries in controller itself. While at the same time I have also read in msdn once that controller is meant to be short.
Using models I use this approach:
In the controller:
public JsonResult SaveStorageLocation(StorageLocations objStorageLocation)
{
int Result = 0;
try
{
StorageLocationModel objStorageLocationModel = new StorageLocationModel();
if (objStorageLocation.Id == Guid.Empty)
{
Result = objStorageLocationModel.AddStorageLocation(objStorageLocation, SessionUserId);
}
else
{
Result = objStorageLocationModel.UpdateStorageLocation(objStorageLocation, SessionUserId);
}
}
catch (Exception ex)
{
Result = (int)MethodStatus.Error;
}
return Json(Result, JsonRequestBehavior.AllowGet);
}
In Model class:
public int AddStorageLocation(StorageLocations objStorageLocation, Guid CreatedBy)
{
MethodStatus Result = MethodStatus.None;
int DuplicateRecordCount = db.StorageLocations.Where(x => x.Location.Trim().ToLower() == objStorageLocation.Location.Trim().ToLower()).Count();
if (DuplicateRecordCount == 0)
{
objStorageLocation.Id = Guid.NewGuid();
objStorageLocation.CreatedBy = CreatedBy;
objStorageLocation.CreatedOn = DateTime.Now;
objStorageLocation.ModifiedBy = CreatedBy;
objStorageLocation.ModifiedOn = DateTime.Now;
objStorageLocation.Status = (int)RecordStatus.Active;
db.StorageLocations.Add(objStorageLocation);
db.SaveChanges();
Result = MethodStatus.Success;
}
else
{
Result = MethodStatus.MemberDuplicateFound;
}
return Convert.ToInt32(Result);
}
public int UpdateStorageLocation(StorageLocations objStorageLocationNewDetails, Guid ModifiedBy)
{
MethodStatus Result = MethodStatus.None;
int DuplicateRecordCount =
db.StorageLocations.
Where(x => x.Location == objStorageLocationNewDetails.Location &&
x.Id != objStorageLocationNewDetails.Id).Count();
if (DuplicateRecordCount == 0)
{
StorageLocations objStorageLocationExistingDetails = db.StorageLocations.Where(x => x.Id == objStorageLocationNewDetails.Id).FirstOrDefault();
if (objStorageLocationExistingDetails != null)
{
objStorageLocationExistingDetails.Location = objStorageLocationNewDetails.Location;
objStorageLocationExistingDetails.ModifiedBy = ModifiedBy;
objStorageLocationExistingDetails.ModifiedOn = DateTime.Now;
objStorageLocationExistingDetails.Status = (int)RecordStatus.Active;
db.SaveChanges();
Result = MethodStatus.Success;
}
}
else
{
Result = MethodStatus.MemberDuplicateFound;
}
return Convert.ToInt32(Result);
}
Or is it better to write all the code in controller itself?