I have created an MVC 4 and use NHibernate for persisting the model and mapped it with fluent nhibernate. the entity has a "Name" property and mapped like in this way:
Map(x => x.Name).Not.Nullable().Length(100);
I have created a table for viewing the list of objects and let me to edit, view object details and delete them. when I delete the object it the view tier post back the model Id to the corresponding controller and controller via the repository object tries to delete the object.
[HttpPost]
public ActionResult DeleteElement(Element element)
{
Element deletedElement = repository.Delete(element);
TempData["message"] = string.Format("{0} has been deleted.",deletedElement.Name);
return RedirectToAction("Index");
}
the partial of table view:
<td>
@using (Html.BeginForm("DeleteMenu", "Admin"))
{
@Html.Hidden("ID", item.ID)
<input type="submit" value="Delete"/>
}
</td>
So the view only post back the elemntID to the controller. and element object has only its ID. and all of its properties are null.when trying to delete the object because the name property is null, the session object in the repository can't delete the object because name field is null.
the Error message:
not-null property references a null or transient value Element.Name
If I am only removing an object and have the primary key, why does nHibernate care if other fields are null? and how can I delete the object only with its id?
public IQueryable<T> GetAll()
{
return session.Query<T>();
}
public IQueryable<T> Get(Expression<Func<T, bool>> predicate)
{
return GetAll().Where(predicate);
}
public void Delete(T entity)
{
session.Delete(entity);
}