我正在使用Fluent NHibernate处理带有外键的基本CRUD。
每次我从视图中调用Delete()
;似乎代码执行成功。但是,它什么也没做。没有例外。
Delete()
方法适用于Provider
模型,但不适用于Product
。
我的应用使用MVC 5.
型号:
Provider.cs:
public class Provider
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Address { get; set; }
public virtual string Phone { get; set; }
public virtual string Email { get; set; }
public virtual IList<Product> Products { get; set; }
public Provider()
{
Products = new List<Product>();
}
}
Product.cs:
public class Product
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual DateTime ManufacturingDate { get; set; }
public virtual DateTime ExpirationDate { get; set; }
public virtual double Weight { get; set; }
public virtual double Price { get; set; }
public virtual double NetProfit { get; set; }
public virtual int Quantity { get; set; }
public virtual Provider Provider { get; set; }
public virtual IList<Detail> Details { get; set; }
public Product()
{
Details = new List<Detail>();
}
}
映射:
ProviderMap.cs:
public class ProviderMap : ClassMap<Provider>
{
public ProviderMap()
{
Id(x => x.Id, "id");
Map(x => x.Name, "name");
Map(x => x.Address, "address");
Map(x => x.Phone, "phone");
Map(x => x.Email, "email");
HasMany(x => x.Products)
.Inverse()
.Cascade.Persist()
.Not.LazyLoad();
}
}
ProductMap.cs:
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
Id(x => x.Id, "id").GeneratedBy.Assigned();
Map(x => x.Name, "name");
Map(x => x.ManufacturingDate, "manufacturing_date");
Map(x => x.ExpirationDate, "expiration_date");
Map(x => x.Weight, "weight");
Map(x => x.Price, "price");
Map(x => x.NetProfit, "net_profit");
Map(x => x.Quantity, "quantity");
References(x => x.Provider, "provider_id").Not.LazyLoad();
HasMany(x => x.Details)
.Inverse()
.Cascade.Persist()
.Not.LazyLoad();
}
}
Delete()方法:
public void Delete(T entity)
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Delete(entity);
transaction.Commit();
}
}
}
呼叫:
// GET: Product/Delete/5
public ActionResult Delete(int id)
{
var product = _productRepository.Find(id);
return View(product);
}
// POST: Product/Delete/5
[HttpPost]
public ActionResult Delete(int id, Product product)
{
try
{
_productRepository.Delete(product);
return RedirectToAction("Index");
}
catch(Exception e)
{
throw;
}
}