Get recent inserted Id and send in to another controllers view - asp.net-mvc

EDITED:
I have Created CRUD Functions for each Modals and now i am trying to get recent Inserted Id and use it in different view.
Here is what I have tried so far
I have created 2 classes(Layer based) for CRUD function for each ContextEntities db to practice pure OOP recursive approach and following is the code.
1. Access Layer
ViolatorDB
public class ViolatorDB
{
private TPCAEntities db;
public ViolatorDB()
{
db = new TPCAEntities();
}
public IEnumerable<tbl_Violator> GetALL()
{
return db.tbl_Violator.ToList();
}
public tbl_Violator GetByID(int id)
{
return db.tbl_Violator.Find(id);
}
public void Insert(tbl_Violator Violator)
{
db.tbl_Violator.Add(Violator);
Save();
}
public void Delete(int id)
{
tbl_Violator Violator = db.tbl_Violator.Find(id);
db.tbl_Violator.Remove(Violator);
Save();
}
public void Update(tbl_Violator Violator)
{
db.Entry(Violator).State = EntityState.Modified;
Save();
}
public void Save()
{
db.SaveChanges();
}
}
2. Logic Layer
ViolatorBs
public class ViolatorBs
{
private ViolatorDB objDb;
public ViolatorBs()
{
objDb = new ViolatorDB();
}
public IEnumerable<tbl_Violator> GetALL()
{
return objDb.GetALL();
}
public tbl_Violator GetByID(int id)
{
return objDb.GetByID(id);
}
public void Insert(tbl_Violator Violator)
{
objDb.Insert(Violator);
}
public void Delete(int id)
{
objDb.Delete(id);
}
public void Update(tbl_Violator Vioaltor)
{
objDb.Update(Vioaltor);
}
}
And Finally using Logic Layer functions in presentation Layer.Here insertion is performed as:
public class CreateViolatorController : Controller
{
public TPCAEntities db = new TPCAEntities();
private ViolatorBs objBs;
public CreateViolatorController()
{
objBs = new ViolatorBs();
}
public ActionResult Index()
{
var voilator = new tbl_Violator();
voilator=db.tbl_Violator.Add(voilator);
ViewBag.id = voilator.VID;
return View();
}
[HttpPost]
public ActionResult Create(tbl_Violator Violator)
{
try
{
if (ModelState.IsValid)
{
objBs.Insert(Violator);
TempData["Msg"] = "Violator Created successfully";
return RedirectToAction("Index");
}
else
{
return View("Index");
}
}
catch (Exception ex)
{
TempData["Msg"] = "Failed..." + ex.Message + " " + ex.ToString();
return RedirectToAction("Index");
}
}
}
Now here is the main part how do i get perticuller inserted id in another controller named Dues while performing insertion ?
In sqlqery I would have used ##IDENTITY but in Entity Framework I'm not sure.
I'm new to mvc framework any suggestion or help is appreciated Thanks in Advance.

Once you save your db context the id is populated back to your entity by EF automatically.
for example.
using(var context = new DbContext())
{
var employee = new Employee(); //this has an id property
context.Employees.Add(employee);
context.SaveChanges();
var id = employee.id; // you will find the id here populated by EF
}

You dont need to add and save your table as you have done this already in your voilatorDB class just fetch the last id like following
var id = yourTableName.Id;
db.yourTableName.find(id);
Or you can simply write one line code to achive that using VoilatorBs class function
GetbyID(id);

Related

dependency injection - convert ninject di to lightinject di

How do I convert the following Ninject DI to the equivalent for LightInject DI? I'm having issues with getting to the right syntax.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
kernel.Bind<UserAccountService>().ToSelf();
kernel.Bind<AuthenticationService>().To<SamAuthenticationService>();
kernel.Bind<IUserAccountQuery>().To<DefaultUserAccountRepository>().InRequestScope();
kernel.Bind<IUserAccountRepository>().To<DefaultUserAccountRepository>().InRequestScope();
On my original question, I didn't include this, but this (also posted as comment to this post) was the not working code I attempted to make it work:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
container.Register<UserAccountService>();
container.Register<AuthenticationService, SamAuthenticationService>();
container.Register<IUserAccountQuery, DefaultUserAccountRepository>(new PerRequestLifeTime());
container.Register<IUserAccountRepository, DefaultUserAccountRepository>(new PerRequestLifeTime());
The error message (without the stack trace) given was this:
Exception Details: System.InvalidOperationException: Unresolved dependency [Target Type: BrockAllen.MembershipReboot.Ef.DefaultUserAccountRepository], [Parameter: ctx(BrockAllen.MembershipReboot.Ef.DefaultMembershipRebootDatabase)], [Requested dependency: ServiceType:BrockAllen.MembershipReboot.Ef.DefaultMembershipRebootDatabase, ServiceName:]
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
*If anyone wants to see the stack trace too - * just ask, and I'll post it in a reply to this question.
The constructor for DefaultMembershipRebootDatabase (as was in a sample project, my project used the dll provided through nuget, and the constructor wasn't available, but I'm pretty sure they're more than likely the same in both cases (seeing as how it comes from the same source...) is:
public class DefaultMembershipRebootDatabase : MembershipRebootDbContext<RelationalUserAccount>
{
public DefaultMembershipRebootDatabase()
: base()
{
}
public DefaultMembershipRebootDatabase(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public DefaultMembershipRebootDatabase(string nameOrConnectionString, string schemaName)
: base(nameOrConnectionString, schemaName)
{
}
}
This is the constructor (as was in the same aforementioned sample project) for the DefaultUserAccountRepository:
public class DefaultUserAccountRepository
: DbContextUserAccountRepository<DefaultMembershipRebootDatabase, RelationalUserAccount>,
IUserAccountRepository
{
public DefaultUserAccountRepository(DefaultMembershipRebootDatabase ctx)
: base(ctx)
{
}
IUserAccountRepository<RelationalUserAccount> This { get { return (IUserAccountRepository<RelationalUserAccount>)this; } }
public new UserAccount Create()
{
return This.Create();
}
public void Add(UserAccount item)
{
This.Add((RelationalUserAccount)item);
}
public void Remove(UserAccount item)
{
This.Remove((RelationalUserAccount)item);
}
public void Update(UserAccount item)
{
This.Update((RelationalUserAccount)item);
}
public new UserAccount GetByID(System.Guid id)
{
return This.GetByID(id);
}
public new UserAccount GetByUsername(string username)
{
return This.GetByUsername(username);
}
UserAccount IUserAccountRepository<UserAccount>.GetByUsername(string tenant, string username)
{
return This.GetByUsername(tenant, username);
}
public new UserAccount GetByEmail(string tenant, string email)
{
return This.GetByEmail(tenant, email);
}
public new UserAccount GetByMobilePhone(string tenant, string phone)
{
return This.GetByMobilePhone(tenant, phone);
}
public new UserAccount GetByVerificationKey(string key)
{
return This.GetByVerificationKey(key);
}
public new UserAccount GetByLinkedAccount(string tenant, string provider, string id)
{
return This.GetByLinkedAccount(tenant, provider, id);
}
public new UserAccount GetByCertificate(string tenant, string thumbprint)
{
return This.GetByCertificate(tenant, thumbprint);
}
}
And this is the controller in my project:
namespace brockallen_MembershipReboot.Controllers
{
using System.ComponentModel.DataAnnotations;
using BrockAllen.MembershipReboot;
using BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Models;
public class UserAccountController : Controller
{
UserAccountService _userAccountService;
AuthenticationService _authService;
public UserAccountController(AuthenticationService authService)
{
_userAccountService = authService.UserAccountService;
_authService = authService;
}
// GET: /UserAccount/
[Authorize]
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return View(new LoginInputModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginInputModel model)
{
if (ModelState.IsValid)
{
/*BrockAllen.MembershipReboot.*/UserAccount account;
if (_userAccountService.AuthenticateWithUsernameOrEmail(model.Username, model.Password, out account))
{
_authService.SignIn(account, model.RememberMe);
_authService.SignIn(account, model.RememberMe);
/*if (account.RequiresTwoFactorAuthCodeToSignIn())
{
return RedirectToAction("TwoFactorAuthCodeLogin");
}
if (account.RequiresTwoFactorCertificateToSignIn())
{
return RedirectToAction("CertificateLogin");
}
if (_userAccountService.IsPasswordExpired(account))
{
return RedirectToAction("Index", "ChangePassword");
}*/
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Invalid Username or Password");
}
}
return View(model);
}
public ActionResult Register()
{
return View(new RegisterInputModel());
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Register(RegisterInputModel model)
{
if (ModelState.IsValid)
{
try
{
var account = _userAccountService.CreateAccount(model.Username, model.Password, model.Email);
ViewData["RequireAccountVerification"] = _userAccountService.Configuration.RequireAccountVerification;
return View("Success", model);
}
catch (ValidationException ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return View(model);
}
}
}
The constructor for AuthenicationService is:
public abstract class AuthenticationService : AuthenticationService<UserAccount>
{
public new UserAccountService UserAccountService
{
get { return (UserAccountService)base.UserAccountService; }
set { base.UserAccountService = value; }
}
public AuthenticationService(UserAccountService userService)
: this(userService, null)
{
}
public AuthenticationService(UserAccountService userService, ClaimsAuthenticationManager claimsAuthenticationManager)
: base(userService, claimsAuthenticationManager)
{
}
}
By default, LightInject does not resolve concrete classes without registering them, while NInject does.
For example, NInject can resolve DefaultMembershipRebootDatabase without registering it, while LightInject cannot by default. Take a look at this.
In any way, to fix your issue, make sure that you register your concrete classes (that are needed as dependencies in other classes). Here is an example:
container.Register<DefaultMembershipRebootDatabase>();
I am assuming here that some class has a dependency on the concrete class DefaultMembershipRebootDatabase. If you have other concrete class dependencies, make sure that you also register them.
You should use the PerScopeLifetime rather than the PerRequestLifetime. PerRequestLifetime represents a transient lifetime that tracks disposable instances and disposes them when the scope ends. PerScopeLifetime ensures the same instance within a scope which in this case means the same instance within a web request.

controller post actionresult not saving changes to database

I have a post method in my controller that is not saving changes to my database (SQL express). I am using viewmodels and valueinjector to populate the VM from my model. I have checked and the values in the viewmodel and they have changed, but when I call my service:
fixedAssetService.SaveFixedAsset()
and bookmark the following in the service interface:
unitOfWork.Commit()
and pull up the quick watch window for unitOfWork, it has the old value.
All my tables have primary keys and I am using code first. The connection string is valid becasue I can get the items, I just can't save them.
My post method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(FixedAssetViewModel evm)
{
var fixedAsset = fixedAssetService.GetFixedAsset(evm.FixedAssetId);
// Use Injector to handle mapping between viewmodel and model
fixedAsset.InjectFrom(evm);
try
{
if (ModelState.IsValid)
{
fixedAssetService.SaveFixedAsset();
return RedirectToAction("Details", "FixedAsset", new { id = fixedAsset.FixedAssetId });
}
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
My Service:
namespace FixedAssets.Services
{
public interface IFixedAssetService
{
IEnumerable<FixedAsset> GetAll();
IEnumerable<FixedAsset> FindBy(Expression<Func<FixedAsset, bool>> predicate);
FixedAsset GetFixedAsset(string id);
void CreateFixedAsset(FixedAsset fixedAsset);
void DeleteFixedAsset(string id);
void SaveFixedAsset();
bool ValueInUse(Expression<Func<FixedAsset, bool>> predicate);
}
public class FixedAssetService : IFixedAssetService
{
private readonly IFixedAssetRepository fixedAssetRepository;
private readonly IUnitOfWork unitOfWork;
public FixedAssetService(IFixedAssetRepository fixedAssetRepository, IUnitOfWork unitOfWork)
{
this.fixedAssetRepository = fixedAssetRepository;
this.unitOfWork = unitOfWork;
}
#region IFixedAssetService Members
public IEnumerable<FixedAsset> GetAll()
{
var fixedAssets = fixedAssetRepository.GetAll();
return fixedAssets;
}
public IEnumerable<FixedAsset> FindBy(Expression<Func<FixedAsset, bool>> predicate)
{
IEnumerable<FixedAsset> query = fixedAssetRepository.FindBy(predicate);
return query;
}
public bool ValueInUse(Expression<Func<FixedAsset, bool>> predicate)
{
IQueryable<FixedAsset> query = fixedAssetRepository.FindBy(predicate).AsQueryable();
int count = query.Count();
return count > 0 ? true : false;
}
public FixedAsset GetFixedAsset(string id)
{
var fixedAsset = fixedAssetRepository.GetById(id);
return fixedAsset;
}
public void CreateFixedAsset(FixedAsset fixedAsset)
{
fixedAssetRepository.Add(fixedAsset);
SaveFixedAsset();
}
public void DeleteFixedAsset(string id)
{
var fixedAsset = fixedAssetRepository.GetById(id);
fixedAssetRepository.Delete(fixedAsset);
SaveFixedAsset();
}
public void SaveFixedAsset()
{
unitOfWork.Commit();
}
#endregion
}
}
Edit: One thing I forgot to mention is this app was modeled almost exactly after an existing app that worked fine. Not sure if I have references messed up or what, but the other app uses the same methods only different entities
I found my problem. In the app I used as a model for this one I was using a separate unity class. My database factory registration was like this:
.RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())
Now I am using Microsoft.Practices.Unity and Unity.Mvc4 so I changed the registration to:
container.RegisterType<IDatabaseFactory, DatabaseFactory>();
per the comments in the bootstrapper class. When I changed it to:
container.RegisterType<IDatabaseFactory, DatabaseFactory>(new HierarchicalLifetimeManager());
per the suggestions on this post:
Stackoverflow thread
it finally worked!

How can I use Entity Framework 6 and my repository to delete multiple records?

I am using Entity Framework 6 and I have a repository looking like the following with the Add and Update methods removed to make it shorter:
public class GenericRepository<T> : IRepository<T> where T : class
{
public GenericRepository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("An instance of DbContext is required to use this repository", "context");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public virtual IQueryable<T> Find(Expression<Func<T, bool>> predicate)
{
return DbSet.Where<T>(predicate);
}
public virtual IQueryable<T> GetAll()
{
return DbSet;
}
public virtual T GetById(int id)
{
//return DbSet.FirstOrDefault(PredicateBuilder.GetByIdPredicate<T>(id));
return DbSet.Find(id);
}
public virtual void Delete(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
DbSet.Attach(entity);
DbSet.Remove(entity);
}
}
public virtual void Delete(int id)
{
var entity = GetById(id);
if (entity == null) return; // not found; assume already deleted.
Delete(entity);
}
}
In my controller I call the repository like this:
public HttpResponseMessage DeleteTest(int id)
{
Test test = _uow.Tests.GetById(id);
if (test == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
try
{
_uow.Tests.Delete(test);
_uow.Commit();
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
This works for a single test but how can I delete for example all tests that have an examId column value of 1 being
that examId is one of the columns in the Test table.
You can create another delete method in your generic repository class, see below:
public virtual void Delete(Expression<Func<T, bool>> predicate)
{
IQueryable<T> query = DbSet.Where(predicate).AsQueryable();
foreach (T obj in query)
{
DbSet.Remove(obj);
}
}
Then you can use it like below, it will delete all records which Id equalsid.
_uow.Test.Delete(n => n.Id = id)
I'm not sure if EF is able to handle multiple delete now given a certain value, but the last time I did this I had to resort to a loop.
public HttpResponseMessage DeleteTest(int id)
{
var testList = _uow.Tests.GetAll().Where(o => o.Id == id);
if (testList.Count() == 0)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
try
{
foreach (var test in testList)
{
_uow.Tests.Delete(test);
}
_uow.Commit();
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
If the "test" table is a foreign table linked to a primary table on the "ID" column, you may want to consider doing a cascading delete in this case.
You can use RemoveRange()
public virtual void Delete(Expression<Func<T,bool>> predicate)
{
var query = Context.Set<T>().Where(predicate);
Context.Set<T>().RemoveRange(query);
}

Validation error about Decimal data type in asp.net mvc

I defined a data type decimal(18,10) for longitute and latitute in my database. But it always said "validation error" when I tried to input and submit my form.
I used LINQ to SQL. Is there some validation rules it generated for me otherwise why I can not input these two with something numbers like "2.34".
Thanks in advance
namespace Nerddinner.Models
{
interface IDinnerRepository
{
IQueryable<Dinner> FindAllDinners();
Dinner GetDinner(int id);
void AddDinner(Dinner dinner);
void UpdateDinner(Dinner dinner);
void DeleteDinner(Dinner dinner);
}
}
namespace Nerddinner.Models
{
public class sqlDinnerRepository: IDinnerRepository
{
dbDataContext db;
public sqlDinnerRepository()
{
db = new dbDataContext();
}
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(x => x.DinnerID == id);
}
public void AddDinner(Dinner dinner)
{
db.Dinners.InsertOnSubmit(dinner);
}
public void UpdateDinner(Dinner dinner)
{
db.SubmitChanges();
}
public void DeleteDinner(Dinner dinner)
{
db.Dinners.DeleteOnSubmit(dinner);
}
}
}
namespace Nerddinner.Controllers
{
public class DinnerController : Controller
{
IDinnerRepository _repository;
public DinnerController()
{
_repository = new sqlDinnerRepository();
}
public DinnerController(IDinnerRepository repository)
{
_repository = repository;
}
//
// GET: /Dinner/
public ActionResult Index()
{
var dinners = _repository.FindAllDinners();
return View(dinners);
}
//
// GET: /Dinner/Details/5
public ActionResult Details(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// GET: /Dinner/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Dinner/Create
[HttpPost]
public ActionResult Create(Dinner dinner)
{
try
{
// TODO: Add insert logic here
_repository.AddDinner(dinner);
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// GET: /Dinner/Edit/5
public ActionResult Edit(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// POST: /Dinner/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var db = new dbDataContext();
var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == id);
try
{
// TODO: Add update logic here
UpdateModel(dinner, collection.ToValueProvider());
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// POST: /Dinner/Delete/5
[HttpPost]
public ActionResult Delete(int id)
{
var db = new dbDataContext();
var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == id);
try
{
// TODO: Add delete logic here
_repository.DeleteDinner(dinner);
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
}
}
Thanks for helping me.
In ASP.NET MVC, You can use the DisplayFormatAttribute on your model property:
[DisplayFormat(DataFormatString = "{0:0.##}")]
public decimal decimalNumber { get; set; }
The above will output a number with up to 2 decimal places.
For more information visit: Custom Numeric Format Strings and Standard Numeric Format Strings
IN SQL SERVER:
*decimal(m,a)*: m is the number of total digits your decimal can have, while a is the max number of decimal points you can have.
so if you put PI into a Decimal(18,0) it will be recorded as 3
if you put PI into a decimal(18,2) it will be recorded as 3.14
if you put PI into Decimal(18,10) be recorded as 3.1415926535
I think my answer will help you. Correct me if I am wrong.

Best Practice for fill ViewModel with different Repositories

I'm trying to find out the best way to doing this code
(because I think, my way locks not good):
I've tried to make it as easy to understand the problem.
public ActionResult Index()
{
var user=new User();
user.load(1);
return View(user);
}
load(int id )
{
//pseudocode:
//1. load user from repository1
//2. load address from repository2
//3.load payments from repository3
}
Here you go
We would first create a UserModelService as below
public class UserModelService
{
public User Load(int id)
{
var userRepository = new UserRepository();
var user = userRepository.Load(id);
var addressRepository = new AddressRepository();
user.Address = addressRepository.LoadForUserId(id);
return user;
}
}
We would then modify the original code in controller as below
public ActionResult Index()
{
var userModelSerice =new UserModelService();
var user = userModelService.load(1);
return View(user);
}
All the remaining code reference above is as below
public class AddressRepository
{
public Address LoadForUserId(int id)
{
// Load the address for given user id
}
}
public class UserRepository
{
public User Load(int id)
{
// Load and return user
}
}
public class User
{
public Address Address { get; set; }
}
public class Address
{
}
Now in your controller action, instead of creating a new instance of UserModelService, you can have it injected through constructor. Similar principle can be applied to inject the repositories into UserModelService but that would be another big discussion so I would cut myself short here.

Resources