Getting 'Specified cast is not valid.' Error on MVC SqlDataReader - asp.net-mvc

Please don't mark this as DUPLICATE QUESTION.
I've been trying to do follow all the answers I have found but I still get this error. Can anyone give me idea where this error came from ??
Here's the error
Server Error in '/NomsPR' Application.
Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Specified cast is not valid.
Source Error:
Line 36: while (reader.Read())
Line 37: {
Line 38: results.Add( new NomsPRItem()
Line 39: {
Line 40: RequestID = reader.GetInt32(0)
Source File: c:\SVN\branches\NomsPRMonitoring\NomsPRMonitoring\Models\CheckerConnection.cs Line: 38
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Int32() +6639748
Lear.NomsPRMonitoring.Models.CheckerConnection.LoadPRItems(DateTime from, DateTime to) in c:\SVN\branches\NomsPRMonitoring\NomsPRMonitoring\Models\CheckerConnection.cs:38
Lear.NomsPRMonitoring.Controllers.CheckerController.GetList() in c:\SVN\branches\NomsPRMonitoring\NomsPRMonitoring\Controllers\CheckerController.cs:33
lambda_method(Closure , ControllerBase , Object[] ) +79
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +261
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +34
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +124
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +838499
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +839052
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Here is my model :
public class NomsPRItem
{
public long RequestID { get; set; }
public long PartID { get; set; }
public string PartNumber { get; set; }
public string PartDesc { get; set; }
public string UnitName { get; set; }
public double PartQuantity { get; set; }
public string CurrName { get; set; }
public double PiecePrice { get; set; }
public DateTime DeliveryDate { get; set; }
public string ProposeSuppliers { get; set; }
public string Comments { get; set; }
public long AccountTypeID { get; set; }
public string AccountType { get; set; }
public string InboxLearUID { get; set; }
public bool ReviewFlag { get; set; }
public long SubCatID { get; set; }
public string SubCatName { get; set; }
public DateTime CreateDate { get; set; }
public string CreateBy { get; set; }
public DateTime LastDate { get; set; }
public string LastBy { get; set; }
public string SupplierID { get; set; }
public string CostCenter { get; set; }
public long SubAccountTypeID { get; set; }
public string SubAccountType { get; set; }
public double TotalAmount { get; set; }
public double Amount { get; set; }
public string ItemId { get; set; }
public string FullName { get; set; }
}
}
And my connection
public static List<NomsPRItem> LoadPRItems(DateTime from, DateTime to)
{
string sSrcipt = m_sReport + "and p.[RequestDate] between '" + from.ToString("yyyy-MM-dd HH:mm:ss") + "' and '" + to.ToString("yyyy-MM-dd HH:mm:ss") + "'";
List<NomsPRItem> results = new List<NomsPRItem>();
using (SqlConnection con = new SqlConnection(m_sConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(sSrcipt, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
results.Add( new NomsPRItem()
{
RequestID = reader.GetInt32(0)
,PartID = reader.GetInt32(15)
,PartDesc = reader.GetString(1)
,PartNumber = reader.GetString(7)
,SupplierID = reader.GetString(16)
,AccountType = reader.GetString(3)
,CurrName = reader.GetString(4)
,PartQuantity = (double)reader.GetDecimal(5)
,PiecePrice = (double)reader.GetDecimal(6)
,Amount = (double)reader.GetDecimal(5) * (double)reader.GetDecimal(6)
});
}
}
}
return results;
}
}
I am using angularjs in this, so I am converting this data to JSON ..
Here is my controller :
public JsonResult GetList()
{
DateTime today = DateTime.Now;
List<NomsPRItem> model = CheckerConnection.LoadPRItems(new DateTime(today.Year, today.Month, 1, 0, 0, 0), today);
return Json(model, JsonRequestBehavior.AllowGet);
}
public JsonResult GetReportList(string from, string to)
{
DateTime fromd = DateTime.Now;
DateTime tod = DateTime.Now;
if (from != "undefined")
fromd = Convert.ToDateTime(from);
if (to != "undefined")
tod = Convert.ToDateTime(to);
fromd = new DateTime(fromd.Year, fromd.Month, fromd.Day, 0, 0, 0);
tod = new DateTime(tod.Year, tod.Month, tod.Day, 23, 59, 59);
return Json(CheckerConnection.LoadPRItems(fromd, tod), JsonRequestBehavior.AllowGet);
}
I hope someone can help me on this mistake !

Your requestID is long and you are converting it to Int32.Change it to Int64 like this.
RequestID = reader.GetInt64(0)
,PartID = reader.GetInt64(15)

Related

ViewModel Mvc Display details

So i have 3 models and need to display information in a view that is on the 3 models, so i created a viewModel that contains the info that i need for the view
model 1:
public class Despesa
{
public int TipoDespesaId { get; set; }
public int DespesaId { get; set; }
[Display(Name = "Descrição da Despesa")]
[Required]
public string DespesaDescricao { get; set; }
[Display(Name = "Valor")]
[Required]
public decimal DespesaValor { get; set; }
public int TipoPagamentoId { get; set; }
[Display(Name = "Data")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
[Required]
public DateTime Data { get; set; }
public TipoDespesa TipoDespesa { get; set; }
public TipoPagamento TipoPagamento { get; set; }
[Display(Name = "Comentário")]
public string Comentario { get; set; }
}
model2:
public class TipoDespesa
{
public int TipoDespesaId { get; set; }
[Display(Name = "Tipo de Despesa")]
[Required]
public string TipoDespesaNome { get; set; }
}
model3:
public class TipoPagamento
{
public int TipoPagamentoId { get; set; }
[Display(Name = "Tipo de Pagamento")]
[Required]
public string TipoPagamentoNome { get; set; }
}
myViewModel:
public class ViewModelDetalhes
{
public string TipoDespesa { get; set; }
public string TipoPagamento { get; set; }
public string Descricao { get; set; }
public decimal Valor { get; set; }
public DateTime Data { get; set; }
public string comentario { get; set; }
}
my Details:
public ActionResult Details(int? id)
{
var modelo = db.Despesas.Where(p => p.DespesaId == id).FirstOrDefault();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (modelo == null)
{
return HttpNotFound();
}
ViewModelDetalhes model = new ViewModelDetalhes()
{
TipoDespesa = modelo.TipoDespesa,
TipoPagamento = modelo.TipoPagamento,
Descricao = modelo.DespesaDescricao,
Valor = modelo.DespesaValor,
comentario = modelo.Comentario,
};
return View(model);
}
I dont know how i can get the values of TipoPagamento and TipoDespesa here should i do a include on the modelo? im a bit confused and need to know how to retrieve the values TipoPagamento and TipoDespesa associated with the main class Despesas.
Thanks
Your ViewModel
public class ViewModelDetalhes
{
public string TipoDespesa{ get; set; }
public string TipoPagamento { get; set; }
public string Descricao { get; set; }
public decimal Valor { get; set; }
public DateTime Data { get; set; }
public string comentario { get; set; }
}
If you want to lazy load make use of Virtual
public class Despesa
{
public int TipoDespesaId { get; set; }
public int DespesaId { get; set; }
[Display(Name = "Descrição da Despesa")]
[Required]
public string DespesaDescricao { get; set; }
[Display(Name = "Valor")]
[Required]
public decimal DespesaValor { get; set; }
public int TipoPagamentoId { get; set; }
[Display(Name = "Data")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
[Required]
public DateTime Data { get; set; }
public virtual TipoDespesa TipoDespesa { get; set; }
public virtual TipoPagamento TipoPagamento { get; set; }
[Display(Name = "Comentário")]
public string Comentario { get; set; }
}
You Detail ActionResult
public ActionResult Details(int? id)
{
var modelo = db.Despesas.Where(p => p.DespesaId == id).FirstOrDefault();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (modelo == null)
{
return HttpNotFound();
}
ViewModelDetalhes model = new ViewModelDetalhes()
{
TipoDespesa = modelo.TipoDespesa.TipoDespesaNome ,
TipoPagamento = modelo.TipoPagamento.TipoPagamentoNome,
Descricao = modelo.DespesaDescricao,
Valor = modelo.DespesaValor,
comentario = modelo.Comentario,
};
return View(model);
}
If you do not want to eager load use include. No need to add virtual to your POCO.
In your Detail ActionResult
public ActionResult Details(int? id)
{
var modelo = db.Despesas.Include("TipoDespesa").Include("TipoPagamento").Where(p => p.DespesaId == id).FirstOrDefault();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (modelo == null)
{
return HttpNotFound();
}
ViewModelDetalhes model = new ViewModelDetalhes()
{
TipoDespesa = modelo.TipoDespesa.TipoDespesaNome ,
TipoPagamento = modelo.TipoPagamento.TipoPagamentoNome,
Descricao = modelo.DespesaDescricao,
Valor = modelo.DespesaValor,
comentario = modelo.Comentario,
};
return View(model);
}
Read More Here: https://msdn.microsoft.com/en-gb/data/jj574232.aspx

How to make EF6 Include() subclass navigation properties for a List of items

I am trying to select a list of Invoices and their subclassed items.
Here are the models:
public class SalesContext : DbContext {
public DbSet<Product> Products { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<InvoiceItem> InvoiceItems { get; set; }
public SalesContext() : base ("DefaultConnection") {
}
}
public class Invoice {
public int Id { get; set; }
public List<InvoiceItem> Items { get; set; }
public Invoice() {
Items = new List<InvoiceItem>();
}
}
public abstract class InvoiceItem {
public int Id { get; set; }
public int Qty { get; set; }
}
public class ProductInvoiceItem : InvoiceItem {
public int ProductId { get; set; }
public Product Product { get; set; }
}
public class Product {
public int Id { get; set; }
public string Name { get; set; }
}
Here's the seed data:
internal sealed class Configuration : DbMigrationsConfiguration<SalesContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(SalesContext context) {
context.Products.AddOrUpdate(p => p.Name,
new Product {Name = "Bible - New Living Translation"},
new Product {Name = "Bible - King James Version"}
);
context.SaveChanges();
context.Invoices.AddOrUpdate(new Invoice {
Items =
new List<InvoiceItem>() {
new ProductInvoiceItem {ProductId = 1},
new ProductInvoiceItem {ProductId = 2}
}
}
, new Invoice {
Items =
new List<InvoiceItem>() {
new ProductInvoiceItem {ProductId = 1}
}
}
);
context.SaveChanges();
}
}
Here, I'm trying to select the data out with its associated subclass properties.
public class SalesController : Controller
{
private SalesContext db = new SalesContext();
// GET: Sales
public ActionResult Index() {
var query = db.Invoices.Include(i => i.Items);
var query2 = query.Include(i => i.Items.OfType<ProductInvoiceItem>().Select(pi => pi.Product));
var list = query2.ToList();
return View(list);
}
}
In the above code sample, query2 is broken. It throws a runtime exception.
System.ArgumentException was unhandled by user code
HResult=-2147024809 Message=The Include path expression must refer
to a navigation property defined on the type. Use dotted paths for
reference navigation properties and the Select operator for collection
navigation properties. Parameter name: path ParamName=path
Source=EntityFramework StackTrace:
at System.Data.Entity.QueryableExtensions.Include[T,TProperty](IQueryable1
source, Expression1 path)
at ParentChildEntityFrameworkStuff.Web.Controllers.SalesController.Index()
in c:\users\brandon.miller\documents\visual studio
2015\Projects\ParentChildEntityFrameworkStuff\ParentChildEntityFrameworkStuff.Web\Controllers\SalesController.cs:line
20
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult
asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult
asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult
asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
InnerException:
If I use query and get rid of the query2 stuff, it returns data, but of course leaves out the Product on the ProductInvoiceItems. The ProductId field is set, so I know it is getting at least the value types for the ProductInvoiceItems. I've tried and tried and searched and searched and have been unable to find a solution for this, arguably, common use-case.
What can I do in order to eagerly load the Product navigation property?

DbUpdateException unhandled when trying to save in POST method of Delivery and Order after editing respectively

I seem to be getting DbUpdateException error on db.SaveChanges() after I edit my Delivery or Order. I'm not sure why, it works fine for Create and Delete.
Am I missing something somewhere? The GET Edit methods work fine for both.
I get this exception error:
System.Data.Entity.Infrastructure.DbUpdateException was unhandled by
user code HResult=-2146233087 Message=An error occurred while
updating the entries. See the inner exception for details.
Source=EntityFramework StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at HealthHabitat.Controllers.DeliveryController.Edit(DeliveryVM model) in c:\Users\Luffy\Desktop\HealthHabitat
V25\HealthHabitat\Controllers\DeliveryController.cs:line 172
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult
asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult
asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult
asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
InnerException: System.Data.Entity.Core.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator
ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T
noChangesResult, Func2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1
func, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions
options, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1
operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions
options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions
options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement
has been terminated.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=242
Procedure=""
Server=(LocalDb)\v11.0
State=3
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b__c(DbCommand
t, DbCommandInterceptionContext1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget
target, Func3 operation, TInterceptionContext interceptionContext,
Action3 executing, Action3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary2
identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
InnerException:
Order Controller POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "OrderID,HospitalID,StaffID,Date,Time,Expected_Date")] Order order)
{
if (ModelState.IsValid)
{
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = order.OrderID });
}
//ViewBag.DeliveryID = new SelectList(db.Deliverys, "DeliveryID", "DeliveryID", order.DeliveryID);
ViewBag.HospitalID = new SelectList(db.Hospitals, "HospitalID", "Name", order.HospitalID);
ViewBag.StaffID = new SelectList(db.Staffs, "StaffID", "First_Name", order.StaffID);
return View(order);
}
Delivery Controller POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(DeliveryVM model)
{
Delivery delivery = new Delivery()
{
DriverID = model.DriverID,
};
db.Deliverys.Add(delivery);
db.SaveChanges();
// save the selected orders based on the ID of the Delivery object
IEnumerable<int> selectedOrders = model.Orders.Where(o => o.IsSelected).Select(o => o.ID);
foreach (int ID in selectedOrders)
{
Order order = db.Orders.Where(o => o.OrderID == ID).FirstOrDefault();
order.DeliveryID = delivery.DeliveryID;
db.Entry(order).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Details", new { id = delivery.DeliveryID });
Order Model:
public int OrderID { get; set; }
[Display(Name = "Hospital")]
public int HospitalID { get; set; }
[Display(Name = "Staff")]
public int StaffID { get; set; }
public int? DeliveryID { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
public DateTime Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Expected_Date { get; set; }
public virtual Hospital Hospital { get; set; }
public virtual Staff Staff { get; set; }
public virtual Delivery Delivery { get; set; }
public virtual ICollection<OrderItem> OrderItems { get; set; }
Delivery Model:
public enum Status
{
Dispatched, Delayed, Delivered
}
public class Delivery
{
public int DeliveryID { get; set; }
[Display(Name = "Driver")]
public int DriverID { get; set; }
public Status Status { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Comment { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Dispatched")]
public DateTime Dispatched_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Dispatched")]
public DateTime Dispatched_Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Delivered")]
public DateTime? Delivered_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Delivered")]
public DateTime? Delivered_Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Delayed")]
public DateTime? Delayed_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Delayed")]
public DateTime? Delayed_Time { get; set; }
public virtual Driver Driver { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
ViewModels:
public enum Status
{
Dispatched, Delayed, Delivered
}
public class DeliveryVM
{
public int? ID { get; set; }
public int DriverID { get; set; }
public Status Status { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Comment { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Dispatched")]
public DateTime Dispatched_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Dispatched")]
public DateTime Dispatched_Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Delivered")]
public DateTime? Delivered_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Delivered")]
public DateTime? Delivered_Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Delayed")]
public DateTime? Delayed_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Delayed")]
public DateTime? Delayed_Time { get; set; }
public SelectList DriverList { get; set; }
public List<OrderVM> Orders { get; set; }
}
public class OrderVM
{
public int ID { get; set; }
public string Name { get; set; }
public string Address_1 { get; set; }
public string Address_2 { get; set; }
public string Address_3 { get; set; }
public string Province { get; set; }
public DateTime Date { get; set; }
public int DeliveryID { get; set; }
public bool IsSelected { get; set; }
}
PLEASE NOTE: I didn't use ViewModels for Edit Order, only for Edit Delivery.
The important part of the error is
Message=The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value`.
Both Delivery and Order have a number of DateTime fields and at least one of them is not being set when you save so their values are 01/01/0001 (i.e. DateTime.MinValue), but your database table field is DATETIME which only has a year range of 1753-9999. To prevent the error, you can change the sql type to DATETIME2 which matches the c# DateTime range.
However, I suspect the real issue is that you really should be setting the DateTime property. Your Edit() POST method has
Delivery delivery = new Delivery()
{
DriverID = model.DriverID,
};
db.Deliverys.Add(delivery);
however an Edit() method suggests your editing and existing object, so it should be
// Get the data model based on the ID of the view model
Delivery delivery = db.Delivery.Find(model.ID);
// Map the view model properties to the data model
delivery.DriverID = model.DriverID;
// Mark as modified and save
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();

How to setup a many to many relationship

I had to change a one to many to a many to many relationship. With the former A user was assigned a companyId upon registering. The only documents they could return from the database was controlled with a where statement in my Web Api. Now that a User can be assigned many companies I need to change that where statement to do the same thing. So far I have created the junction table. I am having problems accessing it and returning it correctly.
Company Class
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public int UserCompanyId { get; set; }
public virtual UserCompany UserCompany { get; set; }
}
UserClass
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public int UserCompanyId { get; set; }
public virtual UserCompany UserCompany { get; set; }
}
Junction Table
public class UserCompany
{
[Key]
public int UCompanyId { get; set; }
public string Id { get; set; }
public int CompanyId { get; set; }
}
ApiController
public IEnumerable<Document> GetDocuments()
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
using (var context = new ApplicationDbContext())
{
return context.UserCompanies
.Where(j => j.CompanyId == user.UserCompany.CompanyId)
.ToList();
}
}
The Error is coming at the .ToList()
Error 1 Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
Update
// GET api/<controller>
public List<Document> GetDocuments()
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
using (var context = new ApplicationDbContext())
{
return context.Documents
.Where(j => j.CompanyId == user.UserCompany.UCompanyId)
.ToList();
}
}
Document Class
public class Document
{
public int DocumentId { get; set; }
public DateTime DocumentDate { get; set; }
public string DocumentUrl { get; set; }
public DateTime DocumentUploadDate { get; set; }
public string DocumentUploadedBy { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
I changed IEnumberable to List. I am still not doing it right,I am getting a error in my ApiController
Non-static method requires a target.
I posted my Document Class as well. I am lost on how to make this work. First time with a many to many relationship
Here is the stacktrace
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me, Object instance, Object& memberValue)
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.TryEvaluatePath(Expression expression, ConstantExpression& constantExpression)
at System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.EvaluateParameter(Object[] arguments)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.b__6()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.b__5()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery1..GetEnumerator>b__0()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at TransparentEnergy.ControllersAPI.apiDocumentUserController.GetDocuments() in c:\Development\TransparentEnergy\TransparentEnergy\ControllersAPI\apiDocumentUserController.cs:line 29
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
I think it's because you're returning a List and the type your function return is IEnumerable, try:
public List<Document> GetDocuments()
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
using (var context = new ApplicationDbContext())
{
return context.UserCompanies
.Where(j => j.CompanyId == user.UserCompany.CompanyId)
.ToList();
}
}

Account Being Reset To Unconfirmed

I have a scenario where user accounts are being reset to unconfirmed and their password hash and security stamp are being set to null. Whenever I resend the confirmation email I receive an error that the token is invalid. This works perfectly fine when creating a new user and sending their confirmation email though.
System.Exception: Invalid token.
at PRISMdev.Controllers.AccountController.AddErrors(IdentityResult result)
at PRISMdev.Controllers.AccountController.<ConfirmEmail>d__d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar)
ResendConfirmEmail
public async Task<ActionResult> ResendConfirmationEmail(string email)
{
ApplicationUser applicationUser = await UserManager.FindByEmailAsync(email);
if (applicationUser == null)
{
return Json(new { success = false });
}
else
{
var code = Url.Encode(await UserManager.GenerateEmailConfirmationTokenAsync(applicationUser.Id));
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = applicationUser.Id, code = code }, protocol: Request.Url.Scheme);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new {area = "", userId = applicationUser.Id, code = code }, protocol: Request.Url.Scheme);
//string callbackUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port) + "/Account/ConfirmEmail?userId=" + Url.Encode(applicationUser.Id) + "&code=" + Url.Encode(code);
EmailHelper newEmail = new EmailHelper();
newEmail.To = applicationUser.Email;
newEmail.Subject = "PRISM-Assoc Confirm Account";
newEmail.BodyText = string.Format("Please click on this link to {0}: {1}", newEmail.Subject, callbackUrl);
newEmail.BodyHtml = "Please confirm your account by clicking here.";
newEmail.SendEmail();
return Json(new { success = true });
}
return View();
}
Confirm Email
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
ViewBag.headerTitle = "Account Confirmed";
if (userId == null || code == null)
{
return View("Error");
}
IdentityResult result = await UserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
//send email for reseting password.
await SendResetPasswordEmail(userId);
return View("ConfirmEmail");
}
else
{
AddErrors(result);
return View();
}
}
Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
Identity Model
public class ApplicationUser : IdentityUser
{
// Setting GridColumn Annotations allows you to use AutoGenerateColumns on view to auto create the Grid based on the model. https://gridmvc.codeplex.com/
[Display(Name = "Name")]
[GridColumn(Title = "Name", SortEnabled = true, FilterEnabled = true, Width = "100")]
public string Name { get; set; }
[Display(Name = "Position")]
[GridColumn(Title = "Position", SortEnabled = true, FilterEnabled = true, Width = "50")]
public string Position { get; set; }
[NotMappedColumn]
public DateTime? RegisteredDate { get; set; }
[Display(Name = "Last Date Visited")]
[GridColumn(Title = "Last Visited", SortEnabled = true, FilterEnabled = true, Width = "40")]
public DateTime? LastVisitDate { get; set; }
[GridColumn(Title = "Org.", SortEnabled = true, Width = "100")]
public int? MemberOrgId { get; set; }
[NotMappedColumn]
public int? SponsorOrgId { get; set; }
[Display(Name = "Profile Picture")]
//[GridColumn(Title = "Profile Pic.", SortEnabled = true, FilterEnabled = true)]
[NotMappedColumn]
public string ProfilePictureSrc { get; set; }
[Display(Name = "Forum Username")]
//[GridColumn(Title = "Forum Username", SortEnabled = true, FilterEnabled = true, Width = "30")]
[NotMappedColumn]
public string ForumUsername { get; set; }
[Display(Name = "Receive System Emails")]
//[GridColumn(Title = "Rec. Sys Emails", SortEnabled = true, Width = "30")]
[NotMappedColumn]
public Boolean ReceiveSystemEmails { get; set; }
//////[ForeignKey("MemberOrgId")]
[NotMappedColumn]
public virtual MemberOrganizations Organization { get; set; }
//////[ForeignKey("SponsorOrgId")]
[NotMappedColumn]
public virtual SponsorOrganizations Sponsor { get; set; }
[Display(Name = "User Img")]
[UIHint("ProfPictureEdit")]
public virtual string ProfilePictureUrl
{
get
{
//TODO: update the folder when it isn't null to the blob location
if (string.IsNullOrEmpty(this.ProfilePictureSrc))
{
return "/Content/Images/userThumb.png";
}
else
{
BlobHelper helper = new BlobHelper();
string url = helper.getImageUrl(this.ProfilePictureSrc, "profilepicture");
return url;
}
}
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
//public DbSet<Users> Users { get; set; }
public DbSet<MemberOrganizations> MemberOrganizations { get; set; }
public DbSet<ServiceCategories> ServiceCategories { get; set; }
public DbSet<SponsorOrganizations> SponsorOrganizations { get; set; }
public DbSet<SponsorServiceCategories> SponsorServiceCategories { get; set; }
public DbSet<MemberProjects> MemberProjects { get; set; }
public DbSet<MemberRFPs> MemberRFPs { get; set; }
public DbSet<OptionTypes> OptionTypes { get; set; }
public DbSet<Options> Options { get; set; }
public DbSet<MemberOrganizationsFundTypes> MemberOrganizationsFundTypes { get; set; }
public DbSet<MemberOrganizationsPlanTypes> MemberOrganizationsPlanTypes { get; set; }
public DbSet<MemberOrganizationsOperatingSystems> MemberOrganizationsOperatingSystems { get; set; }
public DbSet<MemberOrganizationsDatabases> MemberOrganizationsDatabases { get; set; }
public DbSet<BoardAndDirectors> BoardAndDirectors { get; set; }
public DbSet<Pages> Pages { get; set; }
public DbSet<SiteFiles> SiteFiles { get; set; }
public DbSet<Surveys> Surveys { get; set; }
public DbSet<BoardEvents> BoardEvents { get; set; }
public DbSet<PRISMEvent> PRISMEvents { get; set; }
public DbSet<PRISMEventGuestAttendees> PRISMEventGuestAttendees { get; set; }
public DbSet<PRISMEventMemberAttendees> PRISMEventMemberAttendees { get; set; }
public DbSet<PRISMEventSponsorAttendees> PRISMEventSponsorAttendees { get; set; }
public DbSet<CustomEmailsAndMessages> CustomEmailsAndMessages { get; set; }
public DbSet<NonSiteMemberProfile> NonSiteMemberProfile { get; set; }
public DbSet<MemberDues> MemberDues { get; set; }
public DbSet<MemberDuesReceived> MemberDuesReceived { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
identityconfig.cs
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 8,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is: {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}

Resources