Orchard 1.9教程实践:IRepository.Create调用报错求助
IRepository.Create Error in Orchard 1.9 Order Module Let's walk through the most likely issues and fixes based on your code snippet and Orchard 1.9's NHibernate-powered data layer:
1. Incomplete Collection Property Definition
Your Details property is cut off, but it looks like you might have a private setter or missing collection initialization. Orchard's NHibernate integration requires collection properties to have a public/protected setter and be initialized to a concrete collection type to work properly.
Fix your OrderRecord collection property like this:
public virtual IList<OrderDetailRecord> Details { get; set; } = new List<OrderDetailRecord>();
Or use constructor-based lazy initialization if you prefer:
public OrderRecord() { Details = new List<OrderDetailRecord>(); }
2. Missing Parameterless Default Constructor
NHibernate requires all entity records to have a public or protected parameterless constructor. If your OrderRecord doesn't include one, add it immediately:
public OrderRecord() { }
3. Enumeration Mapping Problems
Your OrderStatus enum needs to be properly recognized by NHibernate. In Orchard 1.9, double-check:
- The enum is marked as
public - It uses simple integer-based values (no custom attributes unless you've set up a custom mapper)
- If you're using a custom mapping, ensure the enum is mapped to a compatible database column type (like
int)
4. Uninitialized Required Properties
NHibernate will throw errors if non-nullable properties are left unassigned before calling Create. Make sure all mandatory fields are set:
var newOrder = new OrderRecord { CustomerId = currentCustomerId, // Replace with valid customer ID CreatedAt = DateTime.UtcNow, SubTotal = 49.99m, Vat = 9.99m, Status = OrderStatus.Pending, // Use a valid enum value Details = new List<OrderDetailRecord>() // Initialize even if empty }; _orderRepository.Create(newOrder);
5. Repository Injection & Scope Issues
Ensure you're injecting IRepository<OrderRecord> correctly via constructor injection (avoid manual instantiation) and using it within a valid Orchard work context scope. Example of proper injection in a service:
private readonly IRepository<OrderRecord> _orderRepository; public OrderService(IRepository<OrderRecord> orderRepository) { _orderRepository = orderRepository; }
6. Custom Mapping Configuration Errors
If you've built a custom mapping for OrderRecord (instead of using Orchard's content part system), verify all properties are mapped correctly. For standalone records, you may need to register your mapper in your module's handler or module class to ensure NHibernate recognizes it.
If you can share the exact error message and stack trace, we can narrow this down even further—small details like a "null reference" or "mapping exception" will help pinpoint the root cause instantly!
内容的提问来源于stack exchange,提问作者zaesfgr

