This related to my previous post, even though it was original posted as this post it ran in to another problem to which it was answered. So to avoid complexity i have decided to re-post it with a confirmed single error!
i have the following Create() post method to save a user to mst_users table.
[HttpPost]
public ActionResult Create(CustomerVM custObject)
{
if ( ModelState.IsValid )
{
mst_users user = new mst_users
{
uName=custObject.User,
password=custObject.Password,
dtCreated=DateTime.UtcNow,
isLocked=false
};
db.mst_users.Add(user);
db.SaveChanges();
}
}
}
when the methods executes at db.SaveChanges() it throws the error Object is not set an instance of an object but i have initialzed all required fields for the table but it shows me a field in a view that belongs to another collection but its not part of users table here is the video
here is the user object:
here is the error:
Object reference not set to an instance of an object.
Source of the error
Line 44: </div>
Line 45: <div class="editor-field">
Line 46: #Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
Line 47: #Html.ValidationMessageFor(model => model.NameTitle)
Line 48: </div>
Here is the stack:
[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Customer_Create_cshtml.Execute() in c:\aspmvc4-test\test1\test1\Views\Customer\Create.cshtml:46
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +96
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +259
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +294
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +175
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651796
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
try to do something like this
mst_users user = new mst_users();
user.uName=custObject.User;
user.password=custObject.Password;
user.dtCreated=DateTime.UtcNow;
user.isLocked=false;
db.mst_users.Add(user);
db.SaveChanges();
the problem was solved, even when i tagged the db table dtUpdated as not null and assigned with getDate() i must send a date from client else throws the above error!
Related
Im moving out from Guid to string (HiLo) keys which is suggested by RavenDb docs.
Some of my DomainEvents gets fired inside the constructor so the Id should be known before firing the event. When I was using Guid, I'll just create Guid.NewGuid() to generate Id. But for the HiLo provided by RavenDb, what I did was an extension method to generate keys for me and then pass to my Entity constructor as argument.
RavenDb Version: RavenDb.Client 3.0.30000
Note that this is a copy-paste code I found on the internet :)
public static class RavenDbExtensions
{
public static string GenerateIdFor<T>(this IDocumentSession session)
{
// We need the advanced session in order to ensure that the keys are generated in the correct database.
// session.Advanced.DocumentStore.DatabaseCommands is not sufficient.
var advancedSession = session.Advanced as DocumentSession;
if (advancedSession == null)
throw new InvalidOperationException();
// An entity instance is required to generate a key, but we only have a type.
// In our case, the entities don't have public constructors so we must use reflection.
var entity = Activator.CreateInstance(typeof(T), true);
// Generate an ID using the commands and conventions from the current session
return advancedSession.Conventions.GenerateDocumentKey(
advancedSession.DocumentStore.Identifier,
advancedSession.DatabaseCommands,
entity);
}
}
My controller method.
[HttpPost]
[ValidateAntiForgeryToken]
[Route("add", Name = "courses.add")]
public ActionResult Add(AddViewModel model)
{
if (!ModelState.IsValid)
{
model.Categories = DocumentSession.Query<Category>().ToList();
return View(model);
}
string courseId = DocumentSession.GenerateIdFor<Course>();
var course = Course.Create(
courseId,
model.Title,
CourseCode.FromString(model.Code),
StandardDuration.Create(model.Days, model.HoursPerDay),
model.StandardPrice,
model.CategoryId);
DocumentSession.Store(course);
return RedirectToAction("Add");
}
I have this class with JsonIgnore (Raven.Imports.Newtonsoft.Json) attribute
public class StandardDuration : ValueObject
{
private StandardDuration(int days, int hoursPerDay)
{
Days = days;
HoursPerDay = hoursPerDay;
}
public int Days { get; private set; }
public int HoursPerDay { get; private set; }
public static StandardDuration Create(int days, int hoursPerDay)
{
if (days <= 0)
throw new DomainModelException("Days should be atleast one");
if (hoursPerDay <= 0)
throw new DomainModelException("CreditHours should be greater than zero");
return new StandardDuration(days, hoursPerDay);
}
[JsonIgnore]
public int CreditHours
{
get { return HoursPerDay * Days; }
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Days;
yield return HoursPerDay;
}
}
which throws an error
Attempt by method 'Raven.Client.Document.DocumentConvention.DefaultTypeTagName(System.Type)' to access method 'Raven.Imports.Newtonsoft.Json.Utilities.TypeExtensions.IsGenericType(System.Type)' failed.
UPDATE
I cant reproduce the error on the code above due to same issue but before showing the page.
But Im facing the same issue even on non JsonIgnore decorated classes.
public class Category : Entity
{
private Category() { }
private Category(Guid id, string name)
{
Id = id;
Name = name;
}
public string Name { get; private set; }
public static Category Create(Guid id, string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new DomainModelException("Category name should not be blank or null.");
return new Category(id, name);
}
}
controller action
[HttpPost]
[Route("add", Name = "course_categories.add")]
public ActionResult Add(string name)
{
if (ModelState.IsValid)
{
var courseCategory = Category.Create(Guid.NewGuid(), name);
DocumentSession.Store(courseCategory);
AddSuccessMessage("Course Category created");
return RedirectToRoute("course_categories.add_page");
}
ModelState.AddModelError("", "An error occurred please try again.");
return View();
}
stack trace:
[MethodAccessException: Attempt by method 'Raven.Client.Document.DocumentConvention.DefaultTypeTagName(System.Type)' to access method 'Raven.Imports.Newtonsoft.Json.Utilities.TypeExtensions.IsGenericType(System.Type)' failed.]
Raven.Client.Document.DocumentConvention.DefaultTypeTagName(Type t) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:264
Raven.Client.Document.DocumentConvention.GetTypeTagName(Type type) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:296
Raven.Client.Document.DocumentConvention.DefaultFindFullDocumentKeyFromNonStringIdentifier(Object id, Type type, Boolean allowNull) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:152
Raven.Client.Document.GenerateEntityIdOnTheClient.GetIdAsString(Object entity, Object value, String& id) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:49
Raven.Client.Document.GenerateEntityIdOnTheClient.TryGetIdFromInstance(Object entity, String& id) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:33
Raven.Client.Document.InMemoryDocumentSessionOperations.Store(Object entity) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\InMemoryDocumentSessionOperations.cs:646
Web.Features.CourseCategories.CourseCategoriesController.Add(String name) in E:\Projects\Akademia\Presentation\Web\Features\CourseCategories\CourseCategoriesController.cs:39
lambda_method(Closure , ControllerBase , Object[] ) +104
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9721605
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
In my MVC4 application I'm using MVC FoolProof library
In my Metadata class I have
public class R_DealsMetaData
{
public int ID { get; set; }
public int UserId { get; set; }
public bool CodeGenerated { get; set; }
[Required(ErrorMessage="Please Enter Description")]
[Display(Name="Promotion Name:")]
public string Description { get; set; }
[Required(ErrorMessage = "Please select one Option")]
[Display(Name = "Deal Buy:")]
public int Buy { get; set; }
[Required(ErrorMessage = "Please select one Option")]
[Display(Name = "Deal Free:")]
public int Free { get; set; }
public Nullable<bool> Status { get; set; }
public string Type { get; set; }
[DataType(DataType.Date)]
public System.DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[Required(ErrorMessage = "Please select Expiry Date")]
[Display(Name = "Promotion Expiry Date:")]
public System.DateTime ExpiryDate { get; set; }
[RequiredIf("Type", "P", ErrorMessage = "Please select")]
public Nullable<int> PointEarnType { get; set; }
[RequiredIf("PointEarnType", 2, ErrorMessage = "Please enter value")]
public string PointEarnMealText { get; set; }
[RequiredIf("Type","V",ErrorMessage="Please enter")]
public string VolumeBuyText { get; set; }
[RequiredIf("Type","V",ErrorMessage="Please enter")]
public string VolumeEarnText { get; set; }
}
But at my controller post method an exception has been thrown on db.SaveChanges
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(R_Deals r_deals)
{
if (ModelState.IsValid)
{
db.R_Deals.Add(r_deals);
db.SaveChanges();
}
}
Following are the details of exception
An unexpected exception was thrown during validation of 'PointEarnType' when invoking Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.
Stack Trace Details
[NotImplementedException: The method or operation is not implemented.]
Foolproof.ModelAwareValidationAttribute.IsValid(Object value) +59
System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext) +115
System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext) +29
System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +198
[DbUnexpectedValidationException: An unexpected exception was thrown during validation of 'PointEarnType' when invoking Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.]
System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +299
System.Data.Entity.Internal.Validation.PropertyValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +148
System.Data.Entity.Internal.Validation.EntityValidator.ValidateProperties(EntityValidationContext entityValidationContext, InternalPropertyEntry parentProperty, List`1 validationErrors) +203
System.Data.Entity.Internal.Validation.TypeValidator.Validate(EntityValidationContext entityValidationContext, InternalPropertyEntry property) +105
System.Data.Entity.Internal.Validation.EntityValidator.Validate(EntityValidationContext entityValidationContext) +55
System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items) +299
System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items) +89
System.Data.Entity.DbContext.GetValidationErrors() +289
System.Data.Entity.Internal.InternalContext.SaveChanges() +107
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +53
System.Data.Entity.DbContext.SaveChanges() +52
MOU.Controllers.RDealsController.Create(R_Deals r_deals) in e:\MVC Projects\MouMvc\Controllers\RDealsController.cs:197
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +434
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +50
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +75
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +125
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +68
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690164
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
What should I do in this case? Not getting actually where I am going wrong .
Please Help me! Thanks
Foolproof Validation has problems with EntityFramework.
For more details see this bug report
I am getting this error: [SqlException (0x80131904): Invalid object name 'dbo.UserRoles'.], but I can't catch where error is. I can retrieve other data from other tables, but not this.
conditions are:
connection string in web.config:
<add name="myStoreConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\myStore.mdf';Integrated Security=True" providerName="System.Data.SqlClient" />
context:
public class AdminMyStoreConnection : DbContext
{
public DbSet<UserRole> UserRoles { get; set; }
}
sql script to create database:
CREATE TABLE [dbo].[UserRoles] (
[RoleId] INT IDENTITY (1, 1) NOT NULL,
[RoleName] NVARCHAR (256) NOT NULL,
PRIMARY KEY CLUSTERED ([RoleId] ASC),
UNIQUE NONCLUSTERED ([RoleName] ASC)
);
model:
[Table("UserRoles")]
public class UserRole
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
public string RoleName { get; set; }
}
controller with index view:
private UsersContext db = new UsersContext();
public ActionResult Index()
{
return View(db.Customers.ToList());
}
view:
#using myStore.Helpers
#model IEnumerable<myStore.Areas.Administrator.Models.UserRole>
#{
ViewBag.Title = "Roles management";
}
<h2>Roles management</h2>
<div class="admin-container">
<div class="bcontrol">
<i class="icon-plus-sign"></i> Create New Entry
</div>
#{
var grid = new WebGrid(Model, defaultSort: "RoleId", canSort:true, canPage: true, rowsPerPage:20);
}
#grid.GetHtml(
tableStyle: "tadmin",
alternatingRowStyle: "alt",
selectedRowStyle: "selected-row",
columns:
grid.Columns(
grid.Column("RoleId",
header: "ID " + Html.SortDirection(ref grid, "RoleId"),
style: "tadmin-id"),
grid.Column("RoleName",
header: "Role Name " + Html.SortDirection(ref grid, "RoleName"),
format: #<text><a href="#Url.Action("Details", "Roles", new { id = item.RoleId })" >#item.RoleName</a></text>),
grid.Column("Control", style: "tadmin-control", canSort: false,
format:
#<text><i class="icon-edit"></i> Edit
<i class="icon-list"></i> Details
<i class="icon-minus-sign"></i> Delete</text>)
)
)</div>
and error message:
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.Data.SqlClient.SqlException: Invalid object name 'dbo.UserRoles'.
Source Error:
Line 19: public ActionResult Index()
Line 20: {
Line 21: return View(db.UserRoles.ToList());
Line 22: }
Line 23:
and stack trace:
[SqlException (0x80131904): Invalid object name 'dbo.UserRoles'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action`1 wrapCloseInAction) +1753986
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action`1 wrapCloseInAction)
+5296058 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite) +1379
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource`1 completion, Int32 timeout, Task& task,
Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
+10 System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) +437
[EntityCommandExecutionException: An error occurred while executing
the command definition. See the inner exception for details.]
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) +507
System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext
context, ObjectParameterCollection parameterValues) +730
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1
forMergeOption) +131
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
+36 System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +72
System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +23
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
+40 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369 System.Linq.Enumerable.ToList(IEnumerable`1
source) +58
myStore.Areas.Administrator.Controllers.RolesController.Index() in
d:.projects\trains\myStore\myStore\Areas\Administrator\Controllers\RolesController.cs:21
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary`2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary`2
parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.b__41()
+28 System.Web.Mvc.Async.<>c__DisplayClass8`1.b__7(IAsyncResult
_) +10 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.b__33()
+57 System.Web.Mvc.Async.<>c__DisplayClass4f.b__49()
+223 System.Web.Mvc.Async.<>c__DisplayClass37.b__36(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult`1.End()
+57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult
asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.b__20()
+24 System.Web.Mvc.Async.<>c__DisplayClass25.b__22(IAsyncResult
asyncResult) +102 System.Web.Mvc.Async.WrappedAsyncResult`1.End()
+57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult
asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.b__18(IAsyncResult
asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.b__3(IAsyncResult
asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+47 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+9628700 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
The problem was unfortunately very simple - as i have 2 areas - main and administrator and respectively i have 2 types of data connection, i have only 1 connection string in webconfig. after i added second line for admin context and all works
thanks for attention )
so the problem was incomplete (misconfiguration) in webconfig
This usually simply means a configuration issue
perhaps there genuinely is no such table
perhaps the table is there, but isn't the the dbo scheme
perhaps the db is case-sensitive (make sure that both table names are spelled correctly
Source
Your table name in database must be the exactly same with dbSet<> name in dbContext if not rerun the migration. (running update-databse before declaring the dbSets can lead to that problem)
Like below
I'm trying to implement table-per-hierarchy approach, using FluentNHibernate AutoMapping.
I have a base class and three child classes. The third child class overrides a couple of properties of the base class. Instances of first two child classes save fine, but when I try to save an instance of the third class with overridden properties I get
Invalid index 7 for this SqlParameterCollection with Count=7.
It seems NHibernate doesn't add SqlParamaters for overridden properties, but it tries to set a value.
How to fix that? Maybe some changes in mapping/configuration?
The StackTrace:
[IndexOutOfRangeException: Invalid index 7 for this SqlParameterCollection with Count=7.]
System.Data.SqlClient.SqlParameterCollection.RangeCheck(Int32 index) +5033831
System.Data.SqlClient.SqlParameterCollection.GetParameter(Int32 index) +21
System.Data.Common.DbParameterCollection.System.Collections.IList.get_Item(Int32 index) +10
NHibernate.Type.DateTimeType.Set(IDbCommand st, Object value, Int32 index) +74
NHibernate.Type.NullableType.NullSafeSet(IDbCommand cmd, Object value, Int32 index) +70
NHibernate.Type.NullableType.NullSafeSet(IDbCommand st, Object value, Int32 index, Boolean[] settable, ISessionImplementor session) +37
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object id, Object[] fields, Object rowId, Boolean[] includeProperty, Boolean[][] includeColumns, Int32 table, IDbCommand statement, ISessionImplementor session, Int32 index) +189
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) +498
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session) +166
NHibernate.Action.EntityInsertAction.Execute() +181
NHibernate.Engine.ActionQueue.Execute(IExecutable executable) +42
NHibernate.Engine.ActionQueue.ExecuteActions(IList list) +59
NHibernate.Engine.ActionQueue.ExecuteActions() +16
NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) +121
NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) +92
NHibernate.Impl.SessionImpl.Flush() +291
MDT.Core.DataAccess.DbContext.Flush() in C:\dev\DHL\ISS\Common\MDT.Core\DataAccess\DbContext.cs:215
ISS.Web.Controllers.ReportScheduleController.Index() in C:\dev\DHL\ISS\ISS.Web\Controllers\ReportScheduleController.cs:55
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862381
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Yes, FluentNHibernate AutoMapping adds duplicate mapping for overridden properties.
It is strange that the code doesn't help
.Override<ThirdClass>(map => { map.IgnoreProperty(p => p.Age); })
So I have to use
.OverrideAll(map => map.IgnoreProperties(x => x.MemberInfo.HasAttribute<IgnoreMapAttribute>()))
and set [IgnoreMap] attribute in my class.
I am trying to get ServiceStacks Authentication to work on an MVC site. My controllers are like this:
public abstract class ControllerBase : ServiceStackController<AuthUserSession> {
//TODO: override LoginRedirectUrl
}
public class IndexController : ControllerBase {
[Authenticate]
public ActionResult Index() {
return View();
}
}
The first time I test the code by starting the site from Visual Studio, a redirect to the /login route is made.
Now if I start the site again from Visual Studio, the null reference exception shown below is thrown, and this happens on every restart until I delete all cookies in my browser.
Looks like an error?
NullReferenceException: Object reference not set to an instance of an object.]
ServiceStack.Mvc.ServiceStackController`1.get_UserSession() in C:\src\ServiceStack\src\ServiceStack.FluentValidation.Mvc3\Mvc\ServiceStackController.cs:28
ServiceStack.Mvc.ServiceStackController`1.get_AuthSession() in C:\src\ServiceStack\src\ServiceStack.FluentValidation.Mvc3\Mvc\ServiceStackController.cs:39
ServiceStack.Mvc.ExecuteServiceStackFiltersAttribute.OnActionExecuting(ActionExecutingContext filterContext) in C:\src\ServiceStack\src\ServiceStack.FluentValidation.Mvc3\Mvc\ExecuteServiceStackFiltersAttribute.cs:21
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +47
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Ok never mind. The errors I experienced was probably because I had not implemented the login route yet.