I'm using EF Core 2.2.4 and I'm trying to insert datas through an asp.net MVC page.
Here's my repository insert command:
public int InsertFatorMarkup(int empId, GmPreFamFatMkp gmPreFamFatMkp, int usuId)
{
using (var transaction = _GFazContext.Database.BeginTransaction())
{
try
{
var preFamFatId = EtapaInsertFator(empId, gmPreFamFatMkp, usuId);
transaction.Commit();
return preFamFatId;
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
}
}
//Fernando Milanez 28/11/2019
private int EtapaInsertFator(int empId, GmPreFamFatMkp gmPreFamFatMkp, int usuId)
{
gmPreFamFatMkp = RecargaDeDependenciasFator(empId, gmPreFamFatMkp);
gmPreFamFatMkp.PreFamFatId = NextFatorMkpId(gmPreFamFatMkp.PreId, empId);
gmPreFamFatMkp.RegrasNegocio(usuId);
_GFazContext.GmPreFamFatMkp.Add(gmPreFamFatMkp);
_GFazContext.SaveChanges();
return gmPreFamFatMkp.PreFamFatId;
}
//Fernando Milanez 28/11/2019
private GmPreFamFatMkp RecargaDeDependenciasFator(int empId, GmPreFamFatMkp gmPreFamFatMkp)
{
gmPreFamFatMkp.GmPreTab = GetById(empId, gmPreFamFatMkp.PreId);
//gmPreFamFatMkp.GmPreTab = _GFazContext.GmPreTab
// .FirstOrDefault(r => r.EmpId == empId && r.PreId == gmPreFamFatMkp.PreId);
return gmPreFamFatMkp;
}
//Fernando Milanez 28/11/2019
private short NextFatorMkpId(int preId, int empId)
{
var max = _GFazContext.GmPreFamFatMkp
.Where(r => r.PreId == preId)
.Select(r => (int)r.PreFamFatId)
.DefaultIfEmpty(0)
.Max();
return Convert.ToInt16(max + 1);
}
Here's my controller Get and Post methods:
[HttpGet]
public IActionResult FamiliaMarkupInsert(int preId)
{
ViewBag.returnUrl = Request.Headers["Referer"].ToString();
var model = new PreFamFatMkpModel();
model.Form = new GmPreFamFatMkp() { PreId = preId };
model.Form.GmPreTab = _gmPreTabRepositorio.GetById(_empId, preId, false);
model.FamiliaModel = new FamiliaModel();
GetDataCombo(ref model);
return View(model);
}
//Fernando Milanez 29/11/2019
[HttpPost]
public IActionResult FamiliaMarkupInsert(PreFamFatMkpModel model)
{
ViewBag.returnUrl = Request.Headers["Referer"].ToString();
if (ModelState.IsValid)
{
try
{
int newPreFamFatId = _gmPreTabRepositorio.InsertFatorMarkup(_empId, model.Form, _usuId);
return RedirectToAction("TabelaPrecoTabs", new { id = model.Form.PreId, tabName= "Markup Por Família" });
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
if (ex.InnerException != null) ModelState.AddModelError("", ex.InnerException.Message);
}
}
GetDataCombo(ref model);
model.Form.GmPreTab = _gmPreTabRepositorio.GetById(_empId, model.Form.PreId);
return View(model);
}
Here's my configuration class:
public class GmPreFamFatMkpConfigurations : IEntityTypeConfiguration<GmPreFamFatMkp>
{
public void Configure(EntityTypeBuilder<GmPreFamFatMkp> builder)
{
builder.HasKey(r => new { r.PreFamFatId });
builder.Property(r => r.PreFamFatId).UseSqlServerIdentityColumn();
//Monta Relacionamento 1-N - Colocar somente as dependencias, nesse caso depende da tabela de preço e do produto
builder.HasOne(prepro => prepro.GmPreTab).WithMany(pretab => pretab.GmPreFamFatMkps).HasForeignKey(prepro => prepro.PreId);
builder.HasOne(prefamfatmkp => prefamfatmkp.GmPreTab).WithMany(famtab => famtab.GmPreFamFatMkps).HasForeignKey(prefamfatmkp => prefamfatmkp.PreId);
}
}
And finally, heres my error:
Unable to enter an explicit value for the identity column in table 'GmPreFamFatMkp' when IDENTITY_INSERT is set to OFF.
The error is pretty self explanatory. You've provided a value for the column 'GmPreFamFatMkp' and it is an Identity column (guessing auto-increment) and "Identity_Insert" is off. You probably want to leave it that way. You can't provide a value for this column. Give it null or zero value and let EF and the database figure out the correct value.
Related
i have 2 actions .. one for User and i can add data to User table but for Order table my code didn't works and got catch error
this is my user code (Action in Controller)
[HttpPost]
public ActionResult Register(User user)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
if (blUser.Add(user))
{
return Json(new JsonData() { Success = true });
}
else
{
return Json(new JsonData() { Success = false });
};
}
else
{
return Json(new JsonData() { Success = false });
}
}
and (UserRepository):
public class UserRepository : IDisposable
{
private HairCut.Models.MVCHairDresserDBEntities db = null;
public UserRepository()
{
db = new HairCut.Models.MVCHairDresserDBEntities();
}
public bool Add(HairCut.Models.User entity, bool autoSave = true)
{
try
{
db.Users.Add(entity);
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
else
return false;
}
catch
{
return false;
}
}
i just change User word to Order but when try to insert data to table i got catch and return false
Order code:
[HttpPost]
public ActionResult Reserve(int select, int user,int hdId)
{
Order order = new Order();
order.HairDresserId =hdId;
order.UserId = user;
order.timeCome = (select).ToString();
order.timeNow = DateTime.Now.ToString("dddh");
order.confirm = true;
OrderRepository blOrder = new OrderRepository();
if (blOrder.Add(order))
{
return Json(new JsonData() { Success = true });
}
else
{
return Json(new JsonData() { Success = false });
}
}
OrderRepository is similar UserRepository. so why cant insert ? where is my wrong ?
every time use breackpoint and debug my codes got catch in code return Convert.ToBoolean(db.SaveChanges());
OrderRepository have 2 foreignkey. when i checked entity quick watch, helper show me 2 extra field ( User and HairDresser with null value ) .. maybe i need set value to these ?
or maybe need create MetaData class to check validation like User values ( but i don't think this is my problem )
The model item passed into the dictionary is of type
'System.Data.Entity.DynamicProxies.User_3B687608CE2EBE077B3CAB0EA66E20DFC054F09C758B6620E58A15CACB9B74E5',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1Models.UserPR]'.
Here is my code:
Controller part
public ViewResultBase ListUserPR(int idUser)
{
try
{
UserPRParameters parameters = new UserPRParameters();
parameters.IdUser = idReuniao;
base.SetViewBag(parameters);
var model = this.UserPRServices.FindByUserPR(parameters);
this.ViewBag.IdParameters = parameters.IdParameters;
return this.ListView(model);
}
catch (ValidationException exception)
{
base.AddValidationErrors(exception);
return base.PopUpSuccessView();
}
}
Service Class
public IEnumerable<UserPR> FindByUserPR(UserPRParameters parameters)
{
try
{
var query = base.context.UsersPrs.AsQueryable();
query = query.Where(x => x.IdUser== parameters.IdUser);
return query
.Sort(parameters, x => x.IdUser)
.Paginate(parameters);
}
catch (Exception exception)
{
throw new Exception(this.context.Database.Connection.ConnectionString, exception);
}
}
Partial View _ListUserPR inside View "Management"
#model IEnumerable<UserPR>
#{
var idGrid = "grid" + this.ViewBag.IdParameters ?? string.Empty;
var user = this.Model.FirstOrDefault();
int? userId = 0;
if (null != user)
{
userId= user.IdUser;
}
var grid = new IBM.Web.Helpers
.WebGrid(
//source: this.Model,
id: idGrid, rowsPerPage: this.RowsPerPage,
ajaxUpdateContainerId: idGrid
);
var columns = new WebGridColumn[] {
grid.Column("XXXX", UserPRResources.xxx, style: "center"),
grid.Column("XXXX", UserPRResources.xxx, style: "center"),
grid.Column("XXXXX", UserPRResources.xxx, style: "center"),
....
View Management and your Controller
#model User
#{
var id = "id" + Guid.NewGuid().ToString().Substring(0, 5);
this.ViewBag.Title = UserResources.Management;
}
<div class="box-fields">
#using (Ajax.BeginForm(
this.DefaultActionCreate,
"User",
new DefaultAjaxOptions()
))
{
#Html.Partial("Validation")
section">#Resources.ReuniaoResources.ListUser</h2>
#Html.Partial("ListUserPR")
Controller
public ViewResultBase Management(int id)
{
var model = this.Service.Get(id);
return base.SwitchView(model);
}
Service
public User Get(int id)
{
return this.context.Users.Find(id);
}
I have two tables
User > FK in UserPR
UserPR not have PK - it is the result of two relationship tables (User and PR)
I think you can disable the proxy creation by
Configuration.ProxyCreationEnabled = false;
in the dbcontext constructor
I am trying to get the selected value of three properties of my model, using dropdownlist that populate the next dropdownlist using a script.
So my problem is that I replace the EF code by this:
#Html.DropDownList("AssetID", ViewBag.AssetID as SelectList, "Select a Asset Class", new { id="AssetID" })<br />
<select id="Segment" name="segment"></select><br />
<select id="subAsset" name="SubAsset"></select><br />
Instead of that code that EF gives:
#Html.DropDownList("AssetID", String.Empty)
#Html.DropDownList("SegmentID", String.Empty)
#Html.DropDownList("SubAssetID", String.Empty)
That are three properties (foreign key) of my Model Restriction.
My problem is that now the modelState is not valid and thus the reference of Restriction is not added to the database, maybe I have to DropDownlistFor to bind the selected value to the property bu I don't know how. Also, I can post the script if needed.
My Model Restriction:
public string portefeuille
public int AssetID
public int SegmentID
public int SubAssetID
public int Min
public int Max
My Script for populating dropdown based on previous selected item:
$(function () {
$('#AssetID').change(function () {
$.getJSON('/Restriction/SegmentList/' + $('#AssetID').val(), function (data) {
var items = '<option>Select a Segment</option>';
$.each(data, function (i, segment) {
items += "<option value='" + segment.Value + "'>" + segment.Text + "</option>";
});
$('#Segment').html(items);
});
});
$('#Segment').change(function () {
$.getJSON('/Restriction/SubAssetList/' + $('#Segment').val(), function (data) {
var items = '<option>Select a SubAsset</option>';
$.each(data, function (i, subAsset) {
items += "<option value='" + subAsset.Value + "'>" + subAsset.Text + "</option>";
});
$('#subAsset').html(items);
});
});
});
Here is my RestrictionController:
public class RestrictionController : Controller
{
private RestrictionContext db = new RestrictionContext();
//
// GET: /Restriction/
public ActionResult Index()
{
var restrictions = db.Restrictions.Include(r => r.Asset).Include(r => r.Segment).Include(r => r.SubAsset);
return View(restrictions.ToList());
}
//
// GET: /Restriction/Details/5
public ActionResult Details(int id = 0)
{
Restriction restriction = db.Restrictions.Find(id);
if (restriction == null)
{
return HttpNotFound();
}
return View(restriction);
}
//
// GET: /Restriction/Create
public ActionResult Create()
{
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name");
/*
ViewBag.SegmentID = new SelectList(db.Segments, "SegmentID", "Segment_Name");
ViewBag.SubAssetID = new SelectList(db.SubAssets, "SubAssetID", "SubAsset_Name");
* */
return View();
}
//
// POST: /Restriction/Create
[HttpPost]
public ActionResult Create(Restriction restriction)
{
if (ModelState.IsValid)
{
db.Restrictions.Add(restriction);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name", restriction.AssetID);
/*
ViewBag.SegmentID = new SelectList(db.Segments, "SegmentID", "Segment_Name", restriction.SegmentID);
ViewBag.SubAssetID = new SelectList(db.SubAssets, "SubAssetID", "SubAsset_Name", restriction.SubAssetID);
*/
return View(restriction);
}
//
// GET: /Restriction/Edit/5
public ActionResult Edit(int id = 0)
{
Restriction restriction = db.Restrictions.Find(id);
if (restriction == null)
{
return HttpNotFound();
}
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name", restriction.AssetID);
ViewBag.SegmentID = new SelectList(db.Segments, "SegmentID", "Segment_Name", restriction.SegmentID);
ViewBag.SubAssetID = new SelectList(db.SubAssets, "SubAssetID", "SubAsset_Name", restriction.SubAssetID);
return View(restriction);
}
//
// POST: /Restriction/Edit/5
[HttpPost]
public ActionResult Edit(Restriction restriction)
{
if (ModelState.IsValid)
{
db.Entry(restriction).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Asset_Name", restriction.AssetID);
ViewBag.SegmentID = new SelectList(db.Segments, "SegmentID", "Segment_Name", restriction.SegmentID);
ViewBag.SubAssetID = new SelectList(db.SubAssets, "SubAssetID", "SubAsset_Name", restriction.SubAssetID);
return View(restriction);
}
//
// GET: /Restriction/Delete/5
public ActionResult Delete(int id = 0)
{
Restriction restriction = db.Restrictions.Find(id);
if (restriction == null)
{
return HttpNotFound();
}
return View(restriction);
}
//
// POST: /Restriction/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Restriction restriction = db.Restrictions.Find(id);
db.Restrictions.Remove(restriction);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
public JsonResult SegmentList(int Id)
{
var segment = from s in db.Segments
where s.AssetID == Id
select s;
return Json(new SelectList(segment.ToArray(), "SegmentID", "Segment_Name"), JsonRequestBehavior.AllowGet);
}
public JsonResult SubAssetList(int id)
{
var subAsset = from c in db.SubAssets
where c.SegmentID == id
select c;
return Json(new SelectList(subAsset.ToArray(), "SubAssetID", "SubAsset_Name"), JsonRequestBehavior.AllowGet);
}
public IList<Segment> Getsegment(int AssetID)
{
return db.Segments.Where(m => m.AssetID == AssetID).ToList();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadClassesByAssetId(string Asset_Name)
{
var segmentList = this.Getsegment(Convert.ToInt32(Asset_Name));
var segmentData = segmentList.Select(m => new SelectListItem()
{
Text = m.Segment_Name,
Value = m.AssetID.ToString(),
});
return Json(segmentData, JsonRequestBehavior.AllowGet);
}
}
Thank you for your help!
Firstly, you don't have getters and setter on your model properties.
Secondly, your model has properties SegmentID and subAssetID but you have named the controls Segment and subAsset so they dont match your property names. You need to name them SegmentID and SubAssetID. I strongly recommend use use the strongly typed html helper methods to prevent this, for example #Html.DropDownListFor(m => m.AssetID, ViewBag.AssetID as SelectList, ""Select a Asset Class", null)
I have got following code and I have no clue which proper Unit Test I have write out for those methods and how it can be done. Basically I would like to use NUnit.Framework.
Thank you in advance for ANY clue!
[AllowAnonymous]
public ActionResult ForgotPassword(string id)
{
var model = new ForgotPasswordViewModel();
if (!string.IsNullOrEmpty(id))
{
#region Process Reset Password Key
try
{
var forgotPasswordEvent = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UIDHash == id);
if (forgotPasswordEvent != null)
{
var stringToHash = string.Format("{0}---{1}---{2}", forgotPasswordEvent.UID.ToString(),
forgotPasswordEvent.UserId.ToString(), forgotPasswordEvent.Created.ToString());
var readyHash = SecurityHelper.GetHashString(stringToHash);
if (id == readyHash)
{
var forgotPasswordEventUserId = forgotPasswordEvent.UserId.ToString();
var realUser = AppModel.AspNetUsers.SingleOrDefault(x => x.Id == forgotPasswordEventUserId);
if (realUser != null)
{
var resetPasswordViewModel = new ResetPasswordViewModel();
resetPasswordViewModel.ResetPasswordData = id;
resetPasswordViewModel.UserName = realUser.UserName;
return RedirectToAction("ResetPassword", "Account", resetPasswordViewModel); // ResetPassword(resetPasswordViewModel);
}
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
catch (Exception)
{
}
#endregion
}
#region Check if the user is logged in and fill out fileds for him.
var sessionManager = SessionWrapper.GetFromSession<SessionManager>("_SessionManager");
if (sessionManager != null)
{
var clientId = sessionManager.AppUser.ClientId;
if (clientId != null)
{
model.Email = sessionManager.AppUser.EmailID;
model.UserName = sessionManager.AppUser.UserName;
model.IsLoggedInUser = true;
}
}
#endregion
return View(model);
}
[HttpPost]
[AllowAnonymous]
public ActionResult ForgotPassword(ForgotPasswordViewModel model, FormCollection formCollection)
{
if (ModelState.IsValid)
{
try
{
#region Check user input
var user = AppModel.AspNetUsers.SingleOrDefault(x => x.UserName == model.UserName);
var areErrors = false;
if (user == null)
{
ModelState.AddModelError("UserDoesnotExist", DLMModelEntities.Properties.Resource.UserDoesNotExist);
areErrors = true;
}
if (user.EmailID != model.Email)
{
ModelState.AddModelError("EmailIsWrong", DLMModelEntities.Properties.Resource.EmailIsWrong);
areErrors = true;
}
if (areErrors)
return View(model);
#endregion
#region Send Email and inform user
try
{
var forgotPasswordEvent = new ForgotPasswordEvent();
var resetPasswordEmailUserState = new ResetPasswordEmailUserState();
resetPasswordEmailUserState.ForgotPasswordEventId = Guid.NewGuid();
resetPasswordEmailUserState.UserId = Guid.Parse(user.Id);
resetPasswordEmailUserState.Created = DateTime.Now;
forgotPasswordEvent.UID = resetPasswordEmailUserState.ForgotPasswordEventId;
forgotPasswordEvent.UserId = resetPasswordEmailUserState.UserId;
forgotPasswordEvent.IsSent = false;
forgotPasswordEvent.Created = resetPasswordEmailUserState.Created;
var stringToHash = string.Format("{0}---{1}---{2}", resetPasswordEmailUserState.ForgotPasswordEventId.ToString(),
resetPasswordEmailUserState.UserId.ToString(), resetPasswordEmailUserState.Created.ToString());
forgotPasswordEvent.UIDHash = SecurityHelper.GetHashString(stringToHash);
AppModel.ForgotPasswordEvents.Add(forgotPasswordEvent);
AppModel.SaveChanges();
var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
// Set the MailerModel properties that will be passed to the MvcMailer object.
var m = new MailerModel();
m.UserName = user.UserName;
m.ResetPasswordLink = string.Format("{0}/{1}", Request.Url.AbsoluteUri, forgotPasswordEvent.UIDHash);
m.FromEmail = smtp.From;
m.Subject = AppConfiguration.ResetEmailSubject;
m.ToEmail = model.Email;
var client = new SmtpClientWrapper();
client.SendCompleted += (sender, e) =>
{
if (e.Error != null || e.Cancelled)
{
// Handle Error
}
else
{
try
{
var forgotPasswordEventsToUpdate = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UID == resetPasswordEmailUserState.ForgotPasswordEventId);
if (forgotPasswordEventsToUpdate != null)
{
forgotPasswordEventsToUpdate.IsSent = true;
AppModel.SaveChanges();
}
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
}
};
Mailer.PasswordReset(m).SendAsync(resetPasswordEmailUserState, client);
model.IsResetEMailSent = true;
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
#endregion
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
}
return View(model);
}
As your code looks ltl messed up with more than one responsibility.
For Starter what you can do here is:
Refactor your code into small code snippets and move those dependencies into another classes.
when you will be done with first step you will be able to mock those classes using MOQ or NMock or another framework.
Let me know if you have any doubt in above points.
I really need your help on this guys I am stuck and not sure where to start the fix. So i have this form where the user can select a case and parties. I am supposed save and pass along the values of the selected items. I was able to save the case selections but i am having trouble saving the selected party. Here is my code snippets regarding gathering data and saving them.
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryService:
public void Create(VisitEntry visitEntry,IList<Guid>caseIds, IList<Guid>partyIds )
{
EnsureValid(visitEntry);
_visitEntryRepository.Save(visitEntry);
caseIds = AddCurrentCaseToCases(visitEntry.CaseId, caseIds,partyIds);
foreach (var caseId in caseIds.Distinct())
{
var visit = new Visit {CaseId = caseId, VisitEntryId = visitEntry.VisitEntryId};
_visitService.Create(visit);
}
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
DataContext.SubmitChanges();
}
I am not sure how to get this to save the selected party as it is saving the case information and selected case. Thanks for any feedback!
The save call is a bit earlier so your changes made after your fire SubmitChanges, move the SubmitChanges to the end you should good to go I believe
UPDATE
what I mean is change code like following and see if that helps
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
DataContext.SubmitChanges();
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
}