Orchard Custom Module - Model being picked up by N

2019-04-14 22:56发布

问题:

I'm working on building a custom module in Orchard CMS, and I have the following Controller Action:

public ActionResult Inventory()
{
   var models = _repository.Get<MyModel>();
   return View(new MyViewModel() { MyModels = models.ToList() });
}

Now, when Orchard builds this, an exception occurs, because NHibernate has picked up MyModel because its being looked at as a PartRecord, which I do not want it to be.

The exception is method get_Id should be 'public/protected virtual' or 'protected internal virtual'.

I can add virtual to the properties, but I want to avoid having NHibernate have any part in looking at this object, it is unnecessary.

My question is, how can I add a Model, access that model in a view and suppress Orchard from treating it as a PartRecord? I actually use the model in a separate repository, separate from the Orchard DB.

EDIT: Additional Information

_repository is an IDbRepository, pointing to my own DB instance MyModel is a POCO for my data. I'm trying avoid putting virtual on the properties in MyModel, I have them in here, to illustrate where I'm trying to avoid them.

public interface IDbRepository : IDependency
{
    T Find<T>(long id) where T : class, IActiveRecord;
    bool Update<T>(T record) where T : class, IActiveRecord;
    bool Remove<T>(T record) where T : class, IActiveRecord;
}

public class MyModel : IActiveRecord
{
    [Key]
    public virtual long Id { get; set; }
    public virtual int SupplierProductId { get; set; }
    public virtual int SupplierId { get; set; }
    public virtual int ProductId { get; set; }
}

In addition to this, my module does have a settings part that I've created, that does get stored in Orchard DB and is edited in the site settings. I'm using a handler to control that. However, I've tried removing the handler and a few other things to keep Orchard from taking my object into NHibernate.

回答1:

Orchard auto-mapping configuration assumes that any class will be mapped if the following conditions are met:

  • the namespace ends with ".Models" or ".Records"
  • there is an Id property, with virtual accessors
  • the class is neither sealed nor abstract
  • the class doesn't implement IContent or inherits from ContentPartRecord

So if you prevent any of those criteria from being true, you should be good. For instance, defining your classes in a namespace not ending with .Models or .Records should be sufficient.