我正在努力 http://www.ideliverable.com/blog/writing-an-orchard-webshop-module-from-scratch-part-9
我的果园版本是1.9
OrderRecord.cs
public class OrderRecord
{
public virtual int Id { get; set; }
public virtual int CustomerId { get; set; }
public virtual DateTime CreatedAt { get; set; }
public virtual decimal SubTotal { get; set; }
public virtual decimal Vat { get; set; }
public virtual OrderStatus Status { get; set; }
public virtual IList<OrderDetailRecord> Details { get; private set; }
public virtual string PaymentServiceProviderResponse { get; set; }
public virtual string PaymentReference { get; set; }
public virtual DateTime? PaidAt { get; set; }
public virtual DateTime? CompletedAt { get; set; }
public virtual DateTime? CancelledAt { get; set; }
public virtual decimal Total
{
get { return SubTotal + Vat; }
private set { }
}
public virtual string Number
{
get { return (Id + 1000).ToString(CultureInfo.InvariantCulture); }
private set { }
}
public OrderRecord()
{
Details = new List<OrderDetailRecord>();
}
public virtual void UpdateTotals()
{
var subTotal = 0m;
var vat = 0m;
foreach (var detail in Details)
{
subTotal += detail.SubTotal;
vat += detail.Vat;
}
SubTotal = subTotal;
Vat = vat;
}
没有额外的内容部分类,因为我需要使用id和方法在同一个类中定义。不必创建表的字段设置器被定义为私有。 Total
和Number
Migration.cs
SchemaBuilder.CreateTable("OrderRecord", t => t
.Column<int>("Id", c => c.PrimaryKey().Identity())
.Column<int>("CustomerId", c => c.NotNull())
.Column<DateTime>("CreatedAt", c => c.NotNull())
.Column<decimal>("SubTotal", c => c.NotNull())
.Column<decimal>("Vat", c => c.NotNull())
.Column<string>("Status", c => c.WithLength(50).NotNull())
.Column<string>("PaymentServiceProviderResponse", c => c.WithLength(null))
.Column<string>("PaymentReference", c => c.WithLength(50))
.Column<DateTime>("PaidAt", c => c.Nullable())
.Column<DateTime>("CompletedAt", c => c.Nullable())
.Column<DateTime>("CancelledAt", c => c.Nullable())
);
使用这些字段正确创建表但是当我想在OrderService.cs中使用IRepository.Create(T Entity)方法创建OrderRecord时,它会将未绑定的字段发送到表中。 Total
和Number
。
OrderService.cs
public OrderRecord CreateOrder(int customerId, IEnumerable<ShoppingCartItem> items)
{
if (items == null)
throw new ArgumentNullException("items");
// Convert to an array to avoid re-running the enumerable
var itemsArray = items.ToArray();
if (!itemsArray.Any())
throw new ArgumentException("Creating an order with 0 items is not supported", "items");
var order = new OrderRecord
{
CreatedAt = _dateTimeService.Now,
CustomerId = customerId,
Status = OrderStatus.New
};
_orderRepository.Create(order);
最后一行抛出错误 这是错误日志:
2018-04-20 18:37:15,871 [16] Orchard.Exceptions.DefaultExceptionPolicy - 默认 - 捕获到意外的异常[http://localhost:64607/Orchard.WebShop/Order/Create] NHibernate.Exceptions.GenericADOException:无法插入: [Orchard.Webshop.Models.OrderRecord] [SQL:INSERT INTO Orchard_Webshop_OrderRecord(CustomerId,CreatedAt,SubTotal,Vat, 状态,PaymentServiceProviderResponse,PaymentReference,PaidAt, CompletedAt,CancelledAt,Total,Number)VALUES(?,?,?,?,?,?,?, ?,?,?,?,?);选择SCOPE_IDENTITY()] ---&gt; System.Data.SqlClient.SqlException:无效的列名称“Total”。 列名称“Number”无效。声明无法准备 在System.Data.SqlClient.SqlConnection.OnError(SqlException异常, 布尔值breakConnection,Action
1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 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,布尔&amp; 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,Boolean isInternal,Boolean forDescribeParameterEncryption)at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(的CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,Boolean async,Int32超时,任务&amp; task,Boolean asyncWrite,Boolean inRetry, SqlDataReader ds,Boolean describeParameterEncryptionRequest)at System.Data.SqlClient.SqlCommand.RunExecuteReader(的CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String 方法,TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) 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.System.Data.IDbCommand.ExecuteReader()
1.创建(T实体)in C:\ Users \ Selman \ Orchard-dev \ src \ Orchard \ Data \ Repository.cs:第93行 在Orchard.Data.Repository
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Id.IdentityGenerator.InsertSelectDelegate.ExecuteAndExtract(IDbCommand insert, ISessionImplementor session) at NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder) --- End of inner exception stack trace --- at NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder) at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Boolean[] notNull, SqlCommandInfo sql, Object obj, ISessionImplementor session) at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Object obj, ISessionImplementor session) at NHibernate.Action.EntityIdentityInsertAction.Execute() at NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) at NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object entity, Object id, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event) at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event) at NHibernate.Impl.SessionImpl.Save(Object obj) at Orchard.Data.Repository1.Orchard.Data.IRepository<T>.Create(T entity) in C:\Users\Selman\Orchard-dev\src\Orchard\Data\Repository.cs:line 33
1项)in C:\用户\塞尔曼\果园开发的\ src \ Orchard.Web \模块\ Orchard.Webshop \ SERVICES \ OrderService.cs:行 46在Orchard.Webshop.Controllers.OrderController.Create()中 C:\用户\塞尔曼\果园-dev的\ SRC \ Orchard.Web \模块\ Orchard.Webshop \控制器\ OrderController.cs:线 48在lambda_method(Closure,ControllerBase,Object [])at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller,Object []参数)at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary
at Orchard.Webshop.Services.OrderService.CreateOrder(Int32 customerId, IEnumerable2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 参数)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.WrappedAsyncResultBase
1.End() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult的 asyncResult)at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters&LT;&GT; c__DisplayClass46.b__3f() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters&LT;&GT; c__DisplayClass46.b__3f() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters&LT;&GT; c__DisplayClass46.b__3f()
解决方案
我暂时找到了解决方案。我将Total
和Number
字段转换为方法public virtual decimal Total()
和public virtual string Number()
。它现在可以工作。